package com.sc.nft.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.sc.nft.dao.*;
import com.sc.nft.dto.EcologyHatchConfDao;
import com.sc.nft.dto.EcologyPoolIncreasePointsDTO;
import com.sc.nft.dto.EcologyPoolReducePointsDTO;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO;
import com.sc.nft.entity.req.*;
import com.sc.nft.entity.vo.EcologyPoolGetPoolNameByDaoIdVo;
import com.sc.nft.entity.vo.EcologyPoolHatchCollectionVo;
import com.sc.nft.entity.vo.UserCreatorInfoExcelVO;
import com.sc.nft.entity.vo.ecologypool.*;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.EcologyPoolService;
import com.sc.nft.service.UserCreatorInfoService;
import com.sc.nft.sup.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 刘国航
 * @since 2024/7/15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EcologyPoolServiceImpl implements EcologyPoolService {

    private final EcologyPoolDao ecologyPoolDao;
    private final EcologyPoolSourceDayDao ecologyPoolSourceDayDao;
    private final EcologyPoolSourceDetailDao ecologyPoolSourceDetailDao;
    private final UserInfoDao userInfoDao;
    private final EcologyPoolSourceDao ecologyPoolSourceDao;
    private final EcologyPoolRecordDao ecologyPoolRecordDao;
    private final Redisson redisson;
    private final UserCreatorInfoDao userCreatorInfoDao;
    private final EcologyPoolCommunityServiceRankConfDao ecologyPoolCommunityServiceRankConfDao;
    private final EcologyPoolCommunityServiceRankIncomeConfDao ecologyPoolCommunityServiceRankIncomeConfDao;
    private final EcologyPoolCommunityServiceRankIncomeConditionConfDao ecologyPoolCommunityServiceRankIncomeConditionConfDao;
    private final EcologyPoolCommunityServiceRankDao ecologyPoolCommunityServiceRankDao;
    private final EcologyPoolDaoRankConfDao ecologyPoolDaoRankConfDao;
    private final EcologyPoolDaoRankDao ecologyPoolDaoRankDao;
    private final UserRelevanceDao userRelevanceDao;
    private final UserWorkRoomDao userWorkRoomDao;
    private final UserCityServerCentreDao userCityServerCentreDao;
    private final UserCreatorInfoService userCreatorInfoService;
    private final DigitalCollectionDao digitalCollectionDao;
    private final EcologyHatchConfDao ecologyHatchConfDao;
    private final EcologyPoolRelationConditionBindDao ecologyPoolRelationConditionBindDao;
    private final EcologyPoolPrizeDao ecologyPoolPrizeDao;
    //玛特DAO的id
    private final static Long META_DAO_ID = 6L;


    @Override
    public EcologyPool getDaoPool(Long daoId) {
        return ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, daoId);
    }

    @Override
    public List<UserCreatorInfoExcelVO> excellentBrandDownloadTemplate() {
        return userCreatorInfoService.listUserCreatorByPool();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void excellentBrandBatchAllocatePoints(EcologyPoolOperationTypeEnum typeEnum, String remark, List<EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO> bpd) throws InterruptedException {
        String key = RedisKeyEnum.ECOLOGY_POOL_ALLOCATE.getKey();
        RLock lock = redisson.getLock(key);
        try {
            //尝试数据加锁
            if (!lock.tryLock(10, TimeUnit.SECONDS)) {
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            //流水分配
            doExcellentBrandBatchAllocatePoints(typeEnum, remark, bpd);
        } catch (GlobalRunTimeException e) {
            log.error("优秀品牌池批量分配流水异常,excellentBrandBatchAllocatePoints", e);
            throw e;
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("优秀品牌池批量分配流水释放锁:{}", lock);
            }
        }
    }

    private void doExcellentBrandBatchAllocatePoints(EcologyPoolOperationTypeEnum typeEnum, String remark, List<EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO> apd) {
        //获取优秀品牌生态池
        EcologyPool excellentBrand = ecologyPoolDao.getExcellentBrand();
        if (ObjectUtil.isNull(excellentBrand)) {
            throw new GlobalRunTimeException("优秀品牌总池不存在!");
        }
        //校验发放的积分是否大于品牌池
        checkPlus(typeEnum, apd, excellentBrand);
        //校验扣除积分是否小于账户积分
        checkReduce(typeEnum, apd);

        List<Long> ids = apd.stream().map(EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO::getDaoId).collect(Collectors.toList());
        Map<Long, UserCreatorInfo> creatorInfoMap = userCreatorInfoService.getDaoByIdsToMap(ids);
        //发放积分
        doPlus(excellentBrand, typeEnum, remark, apd, creatorInfoMap);
        //扣减积分
        doReduce(excellentBrand, typeEnum, remark, apd, creatorInfoMap);

    }

    private static void checkPlus(EcologyPoolOperationTypeEnum typeEnum, List<EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO> bpd, EcologyPool excellentBrand) {
        if (typeEnum != EcologyPoolOperationTypeEnum.PLUS) {
            return;
        }
        BigDecimal excellentBrandSum = bpd.stream().map(EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO::getLinkCount).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (excellentBrandSum.compareTo(excellentBrand.getLinkCount()) >= 0) {
            throw new GlobalRunTimeException("发放积分不得大于总池积分");
        }
    }

    private void checkReduce(EcologyPoolOperationTypeEnum typeEnum, List<EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO> bpd) {
        if (typeEnum != EcologyPoolOperationTypeEnum.REDUCE) {
            return;
        }
        List<Long> ids = bpd.stream().map(EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO::getDaoId).collect(Collectors.toList());
        Map<Long, EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO> pointsMap = bpd.stream().collect(Collectors.toMap(EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO::getDaoId, x -> x));

        List<EcologyPool> ecologyPools = ecologyPoolDao.listPoolDataByDaoIds(ids);
        for (EcologyPool ecologyPool : ecologyPools) {
            EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO current = pointsMap.get(ecologyPool.getDaoId());
            if (Objects.isNull(current)) {
                continue;
            }
            if (ecologyPool.getLinkCount().compareTo(current.getLinkCount()) < 0) {
                throw new GlobalRunTimeException(ecologyPool.getDaoId() + "扣除积分不得大于账号当前积分");
            }
        }
    }


    private void doReduce(EcologyPool excellentBrand, EcologyPoolOperationTypeEnum typeEnum, String remark, List<EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO> ecologyPoolExcellentBrandBatchAllocatePointsDaoDTOS, Map<Long, UserCreatorInfo> creatorInfoMap) {
        if (typeEnum != EcologyPoolOperationTypeEnum.REDUCE) {
            return;
        }
        List<EcologyPoolRecord> reduceRecord = new ArrayList<>();

        for (EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO dto : ecologyPoolExcellentBrandBatchAllocatePointsDaoDTOS) {
            if (dto.getLinkCount().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, dto.getDaoId());
            if (ObjectUtil.isNull(ecologyPool)) {
                return;
            }
            String uuid = IdUtil.simpleUUID();
            //获取操作方和被操作方
            String activeOperatorName = getOperatorName(EcologyPoolTypeEnum.EXCELLENT_BRAND, creatorInfoMap, excellentBrand.getDaoId());
            String passiveOperatorName = getOperatorName(EcologyPoolTypeEnum.BRAND, creatorInfoMap, ecologyPool.getDaoId());

            BigDecimal beforeLinkCount = ecologyPool.getLinkCount();
            BigDecimal afterLinkCount = beforeLinkCount.subtract(dto.getLinkCount());
            if (ecologyPoolDao.reduceLikeCount(dto.getLinkCount(), ecologyPool.getId(), ecologyPool.getVersion()) <= 0) {
                throw new GlobalRunTimeException("更新失败");
            }

            excellentBrand = ecologyPoolDao.getById(excellentBrand.getId());
            
            //构建流水记录
            buildPoolRecord(
                    reduceRecord, beforeLinkCount, afterLinkCount, dto.getLinkCount(),
                    typeEnum, EcologyPoolOperationTypeEnum.REDUCE, EcologyPoolTypeEnum.BRAND, EcologyPoolTypeEnum.EXCELLENT_BRAND, uuid, remark,
                    ecologyPool.getDaoId(), ecologyPool.getUserId(), excellentBrand.getDaoId(), excellentBrand.getUserId(), activeOperatorName, passiveOperatorName
            );

            //增加总池
            BigDecimal excellentBrandBeforeLinkCont = excellentBrand.getLinkCount();
            BigDecimal excellentBrandAfterLinkCont = excellentBrandBeforeLinkCont.add(dto.getLinkCount());
            if (ecologyPoolDao.plusLikeCount(dto.getLinkCount(), excellentBrand.getId(), excellentBrand.getVersion()) <= 0) {
                throw new GlobalRunTimeException("总池新增失败!");
            }
            buildPoolRecord(reduceRecord, excellentBrandBeforeLinkCont, excellentBrandAfterLinkCont, dto.getLinkCount(),
                    typeEnum, EcologyPoolOperationTypeEnum.PLUS, EcologyPoolTypeEnum.EXCELLENT_BRAND, EcologyPoolTypeEnum.BRAND, uuid, remark,
                    excellentBrand.getDaoId(), excellentBrand.getUserId(), ecologyPool.getDaoId(), ecologyPool.getUserId(), activeOperatorName, passiveOperatorName
            );
        }
        //保存流水
        if (ecologyPoolRecordDao.batchSaveEcologyPoolRecord(reduceRecord) <= 0) {
            throw new GlobalRunTimeException("流水记录新增失败");
        }

    }


    private void doPlus(EcologyPool excellentBrand, EcologyPoolOperationTypeEnum typeEnum, String remark, List<EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO> epb, Map<Long, UserCreatorInfo> creatorInfoMap) {
        if (typeEnum != EcologyPoolOperationTypeEnum.PLUS) {
            return;
        }
        List<EcologyPoolRecord> plusRecord = new ArrayList<>();

        for (EcologyPoolExcellentBrandBatchAllocatePointsDaoDTO dto : epb) {
            if (dto.getLinkCount().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, dto.getDaoId());
            if (ObjectUtil.isNull(ecologyPool)) {
                ecologyPool = new EcologyPool();
                ecologyPool.setLinkCount(BigDecimal.ZERO);
                ecologyPool.setLinkType(EcologyPoolLinkTypeEnum.POINTS);
                ecologyPool.setDaoId(dto.getDaoId());
                ecologyPool.setPoolType(EcologyPoolTypeEnum.BRAND);
                ecologyPool.setVersion(1);
                ecologyPool.buildPkCode();
                if (!ecologyPool.insert()) {
                    throw new GlobalRunTimeException("更新生态池积分失败");
                }
            }
            String uuid = IdUtil.simpleUUID();
            //获取操作方和被操作方
            String activeOperatorName = getOperatorName(EcologyPoolTypeEnum.EXCELLENT_BRAND, creatorInfoMap, excellentBrand.getDaoId());
            String passiveOperatorName = getOperatorName(EcologyPoolTypeEnum.BRAND, creatorInfoMap, ecologyPool.getDaoId());

            BigDecimal beforeLinkCount = ecologyPool.getLinkCount();
            BigDecimal afterLinkCount = beforeLinkCount.add(dto.getLinkCount());
            if (ecologyPoolDao.plusLikeCount(dto.getLinkCount(), ecologyPool.getId(), ecologyPool.getVersion()) <= 0) {
                throw new GlobalRunTimeException("更新失败");
            }

            excellentBrand = ecologyPoolDao.getById(excellentBrand.getId());

            //构建流水记录
            buildPoolRecord(plusRecord, beforeLinkCount, afterLinkCount, dto.getLinkCount(),
                    typeEnum, EcologyPoolOperationTypeEnum.PLUS, EcologyPoolTypeEnum.BRAND, EcologyPoolTypeEnum.EXCELLENT_BRAND, uuid, remark,
                    ecologyPool.getDaoId(), ecologyPool.getUserId(), excellentBrand.getDaoId(), excellentBrand.getUserId(), activeOperatorName, passiveOperatorName);

            //扣减总池
            BigDecimal excellentBrandBeforeLinkCont = excellentBrand.getLinkCount();
            BigDecimal excellentBrandAfterLinkCont = excellentBrandBeforeLinkCont.subtract(dto.getLinkCount());
            if (ecologyPoolDao.reduceLikeCount(dto.getLinkCount(), excellentBrand.getId(), excellentBrand.getVersion()) <= 0) {
                throw new GlobalRunTimeException("总池扣减失败!");
            }

            buildPoolRecord(plusRecord, excellentBrandBeforeLinkCont, excellentBrandAfterLinkCont, dto.getLinkCount(),
                    typeEnum, EcologyPoolOperationTypeEnum.REDUCE, EcologyPoolTypeEnum.EXCELLENT_BRAND, EcologyPoolTypeEnum.BRAND, uuid, remark,
                    excellentBrand.getDaoId(), excellentBrand.getUserId(), ecologyPool.getDaoId(), ecologyPool.getUserId(), activeOperatorName, passiveOperatorName);
        }
        //保存流水
        if (ecologyPoolRecordDao.batchSaveEcologyPoolRecord(plusRecord) <= 0) {
            throw new GlobalRunTimeException("流水记录新增失败");
        }
    }


    private static void buildPoolRecord(List<EcologyPoolRecord> ecologyPoolRecords, BigDecimal beforeLinkCount, BigDecimal afterLinkCount, BigDecimal linkCount, EcologyPoolOperationTypeEnum operationTypeEnum,
                                        EcologyPoolOperationTypeEnum typeEnum, EcologyPoolTypeEnum sourcePoolType, EcologyPoolTypeEnum targetPoolType,
                                        String uuid, String remark, Long sourceDaoId, Long sourceUserId, Long targetDaoId, Long targetUserId
            , String activeOperatorName, String passiveOperatorName) {
        EcologyPoolRecord excellentBrandRecord = new EcologyPoolRecord();
        excellentBrandRecord.setLinkCount(linkCount);
        excellentBrandRecord.setLinkType(EcologyPoolLinkTypeEnum.POINTS);
        excellentBrandRecord.setBeforeLinkCount(beforeLinkCount);
        excellentBrandRecord.setAfterLinkCount(afterLinkCount);
        excellentBrandRecord.setIsAdd(typeEnum == EcologyPoolOperationTypeEnum.PLUS);
        excellentBrandRecord.setDaoId(sourceDaoId);
        excellentBrandRecord.setUserId(sourceUserId);
        excellentBrandRecord.setPoolType(sourcePoolType);
        excellentBrandRecord.setOperationType(operationTypeEnum);
        excellentBrandRecord.setFlowType(typeEnum == EcologyPoolOperationTypeEnum.PLUS ? EcologyPoolFlowTypeEnum.IN_FLOW : EcologyPoolFlowTypeEnum.OUT_FLOW);
        excellentBrandRecord.setRemark(remark);
        excellentBrandRecord.setSourcePoolType(targetPoolType);
        excellentBrandRecord.setSourceDaoId(targetDaoId);
        excellentBrandRecord.setSourceUserId(targetUserId);
        excellentBrandRecord.setTransactionUuid(uuid);
        excellentBrandRecord.setActiveOperatorName(activeOperatorName);
        excellentBrandRecord.setPassiveOperatorName(passiveOperatorName);
        ecologyPoolRecords.add(excellentBrandRecord);
    }


    private String getOperatorName(EcologyPoolTypeEnum poolTypeEnum, Map<Long, UserCreatorInfo> creatorInfoMap, Long daoId) {
        String operatorName = poolTypeEnum.getDesc();
        if (Objects.equals(poolTypeEnum.getCode(), EcologyPoolTypeEnum.BRAND.getCode())) {
            if (Objects.nonNull(daoId)) {
                UserCreatorInfo userCreatorInfo = creatorInfoMap.get(daoId);
                if (Objects.nonNull(userCreatorInfo)) {
                    operatorName = userCreatorInfo.getDaoName();
                }
            }
        }
        return operatorName;
    }


    @Override
    public Map<Long, EcologyPool> getDaoByIdsToMap(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        List<EcologyPool> ecologyPools = ecologyPoolDao.listPoolDataByDaoIds(ids);
        if (CollectionUtils.isEmpty(ecologyPools)) {
            return Collections.emptyMap();
        }
        return ecologyPools.stream().collect(Collectors.toMap(EcologyPool::getDaoId, x -> x));
    }

    @Override
    public Page<EcologyPoolSourceDayPageVO> sourceDayPage(Integer pageNo, Integer pageSize) {
        return (Page<EcologyPoolSourceDayPageVO>) ecologyPoolSourceDayDao.sourceDayPage(new Page<>(pageNo, pageSize)).convert(ecologyPoolSourceDay -> {
            EcologyPoolSourceDayPageVO ecologyPoolSourceDayPageVO = new EcologyPoolSourceDayPageVO();
            ecologyPoolSourceDayPageVO.setLinkCount(ecologyPoolSourceDay.getLinkCount());
            ecologyPoolSourceDayPageVO.setLinkType(ecologyPoolSourceDay.getLinkType());
            ecologyPoolSourceDayPageVO.setLinkTypeName(ecologyPoolSourceDay.getLinkType().getDesc());
            ecologyPoolSourceDayPageVO.setLinkDate(ecologyPoolSourceDay.getLinkDate());
            return ecologyPoolSourceDayPageVO;
        });
    }

    @Override
    public Page<EcologyPoolSourceDetailVO> sourceDetailPage(Integer pageNo, Integer pageSize, Date linkDate) {
        //region 分页查询
        Page<EcologyPoolSourceDetail> page = ecologyPoolSourceDetailDao.sourceDetailPage(new Page<>(pageNo, pageSize), linkDate);
        //endregion
        //region 组装页码信息
        Page<EcologyPoolSourceDetailVO> resultPage = new Page<>();
        resultPage.setCurrent(page.getCurrent());
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        //endregion
        //region 组装分页数据
        List<EcologyPoolSourceDetail> records = page.getRecords();
        List<EcologyPoolSourceDetailVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            //region 查询账号
            List<Long> userIdList = records.stream().filter(record -> Objects.nonNull(record.getUserId())).map(EcologyPoolSourceDetail::getUserId).distinct().collect(Collectors.toList());
            Map<Long, UserInfo> userInfoMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(userIdList)) {
                List<UserInfo> userInfoList = userInfoDao.getByIdList(userIdList);
                if (CollectionUtil.isNotEmpty(userInfoList)) {
                    userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
                }
            }
            //endregion
            Map<Long, UserInfo> finalUserInfoMap = userInfoMap;
            //region 组装返回数据
            records.forEach(record -> {
                EcologyPoolSourceDetailVO resultRecord = new EcologyPoolSourceDetailVO();
                resultRecord.setUserId(record.getUserId());
                if (Objects.nonNull(record.getUserId())) {
                    UserInfo userInfo = finalUserInfoMap.get(record.getUserId());
                    if (Objects.nonNull(userInfo)) {
                        resultRecord.setUserTel(userInfo.getUserTel());
                        resultRecord.setNickName(userInfo.getNickName());
                    }
                }
                resultRecord.setCollectionId(record.getCollectionId());
                resultRecord.setCollectionName(record.getCollectionName());
                resultRecord.setLinkCount(record.getLinkCount());
                resultRecord.setLinkType(record.getLinkType());
                resultRecord.setLinkTypeName(record.getLinkType().getDesc());
                resultRecords.add(resultRecord);
            });
            //endregion
        }
        resultPage.setRecords(resultRecords);
        //endregion
        return resultPage;
    }

    @Override
    public Page<EcologyPoolSourceVO> sourcePage(Integer pageNo, Integer pageSize, String userTel, String collectionName, EcologyPoolSourceStatusEnum status, Date startTime, Date endTime) {
        //region 查询账号
        Long userId = null;
        if (StrUtil.isNotBlank(userTel)) {
            UserInfo userInfo = userInfoDao.getByUserTel(userTel);
            if (Objects.isNull(userInfo)) {
                return new Page<>(pageNo, pageSize);
            }
            userId = userInfo.getId();
        }
        //endregion
        //region 分页查询
        Page<EcologyPoolSource> page = ecologyPoolSourceDao.sourcePage(new Page<>(pageNo, pageSize), userId, collectionName, status, startTime, endTime);
        //endregion
        //region 组装页码信息
        Page<EcologyPoolSourceVO> resultPage = new Page<>();
        resultPage.setCurrent(page.getCurrent());
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        //endregion
        //region 组装返回数据
        List<EcologyPoolSource> records = page.getRecords();
        List<EcologyPoolSourceVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            //region 账号信息
            List<Long> userIdList = records.stream().filter(record -> Objects.nonNull(record.getUserId())).map(EcologyPoolSource::getUserId).distinct().collect(Collectors.toList());
            Map<Long, UserInfo> userInfoMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(userIdList)) {
                List<UserInfo> userInfoList = userInfoDao.getByIdList(userIdList);
                if (CollectionUtil.isNotEmpty(userInfoList)) {
                    userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
                }
            }
            //endregion
            Map<Long, UserInfo> finalUserInfoMap = userInfoMap;
            records.forEach(record -> {
                EcologyPoolSourceVO resultRecord = new EcologyPoolSourceVO();
                resultRecord.setUserId(record.getUserId());
                if (Objects.nonNull(record.getUserId())) {
                    UserInfo userInfo = finalUserInfoMap.get(record.getUserId());
                    if (Objects.nonNull(userInfo)) {
                        resultRecord.setUserTel(userInfo.getUserTel());
                        resultRecord.setNickName(userInfo.getNickName());
                    }
                }
                resultRecord.setCollectionId(record.getCollectionId());
                resultRecord.setCollectionName(record.getCollectionName());
                resultRecord.setLinkCount(record.getLinkCount());
                resultRecord.setLinkType(record.getLinkType());
                resultRecord.setLinkTypeName(record.getLinkType().getDesc());
                resultRecord.setLinkDay(record.getLinkDay());
                resultRecord.setDailyReleaseLinkCount(record.getDailyReleaseLinkCount());
                resultRecord.setWaitReleaseLinkDay(record.getWaitReleaseLinkDay());
                resultRecord.setStatus(record.getStatus());
                resultRecord.setStartTime(record.getStartTime());
                resultRecords.add(resultRecord);
            });
        }
        resultPage.setRecords(resultRecords);
        //endregion
        return resultPage;
    }

    @Override
    public Page<EcologyPoolRecordVO> recordPage(Integer pageNo, Integer pageSize, EcologyPoolTypeEnum poolType, EcologyPoolFlowTypeEnum flowType, Date startTime, Date endTime, String daoName) {
        Long daoId = null;
        if (StrUtil.isNotBlank(daoName)) {
            UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getDaoByDaoName(daoName);
            if (Objects.isNull(userCreatorInfo)) {
                return new Page<>(pageNo, pageSize);
            }
            daoId = userCreatorInfo.getId();
        }
        Page<EcologyPoolRecord> page = ecologyPoolRecordDao.recordPage(new Page<>(pageNo, pageSize), Collections.singletonList(poolType), flowType, startTime, endTime, daoId, null);
        List<EcologyPoolRecord> records = page.getRecords();
        List<EcologyPoolRecordVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(record -> {
                EcologyPoolRecordVO resultRecord = new EcologyPoolRecordVO();
                resultRecord.setCreateTime(record.getCreateTime());
                resultRecord.setFlowType(record.getFlowType());
                resultRecord.setFlowTypeName(record.getFlowType().getDesc());
                resultRecord.setLinkType(record.getLinkType());
                resultRecord.setLinkTypeName(record.getLinkType().getDesc());
                resultRecord.setLinkCount(record.getLinkCount());
                resultRecord.setAfterLinkCount(record.getAfterLinkCount());
                resultRecord.setSourcePoolType(record.getSourcePoolType());
                resultRecord.setSourcePoolTypeName(record.getPassiveOperatorName());
                resultRecord.setPoolType(record.getPoolType());
                resultRecord.setPoolTypeName(record.getActiveOperatorName());
                resultRecord.setOperationType(record.getOperationType());
                resultRecord.setOperationTypeName(record.getOperationType().getDesc());
                resultRecord.setRemark(record.getRemark());
                resultRecords.add(resultRecord);
            });
        }
        Page<EcologyPoolRecordVO> resultPage = new Page<>();
        resultPage.setCurrent(page.getCurrent());
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean officialAllocatePoints(EcologyPoolOperationTypeEnum operationType, Long excellentBrandCount, Long serviceCenterCount, Long communityNetworkCount, EcologyPoolLinkTypeEnum linkType, String remark) {
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL_ALLOCATE.getKey());
        try {
            if (!lock.tryLock(10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            //校验
            List<EcologyPool> ecologyPoolList = validateOfficialAllocatePoints(operationType, excellentBrandCount, serviceCenterCount, communityNetworkCount, linkType);
            //执行
            doOfficialAllocatePoints(ecologyPoolList, operationType, excellentBrandCount, serviceCenterCount, communityNetworkCount, linkType, remark);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("官方生态池分配/扣除积分异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean excellentBrandAllocatePoints(EcologyPoolOperationTypeEnum operationType, Long daoId, Long linkCount, EcologyPoolLinkTypeEnum linkType, String remark) {
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL_ALLOCATE.getKey());
        try {
            if (!lock.tryLock(10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            //校验
            List<EcologyPool> ecologyPoolList = validateExcellentBrandAllocatePoints(operationType, daoId, linkCount, linkType);
            //执行
            doExcellentBrandAllocatePoints(ecologyPoolList, operationType, daoId, linkCount, linkType, remark);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("官方生态池分配/扣除积分异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Override
    public EcologyPoolFindPointsByDaoVO findPointsByDao(Long daoId, EcologyPoolLinkTypeEnum linkType) {
        EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, linkType, daoId);
        EcologyPoolFindPointsByDaoVO ecologyPoolFindPointsByDaoVO = new EcologyPoolFindPointsByDaoVO();
        ecologyPoolFindPointsByDaoVO.setLinkCount(Objects.nonNull(ecologyPool) ? ecologyPool.getLinkCount() : BigDecimal.ZERO);
        ecologyPoolFindPointsByDaoVO.setLinkType(linkType);
        ecologyPoolFindPointsByDaoVO.setLinkTypeName(linkType.getDesc());
        return ecologyPoolFindPointsByDaoVO;
    }

    @Override
    public List<EcologyPoolGetEnableJoinRankDaoPageVo> getEnableJoinRankDaos() {
        List<UserCreatorInfo> userCreatorInfoList = userCreatorInfoDao.getEnableJoinRankDao();
        List<EcologyPoolGetEnableJoinRankDaoPageVo> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userCreatorInfoList)) {
            userCreatorInfoList.forEach(record -> {
                EcologyPoolGetEnableJoinRankDaoPageVo resultRecord = new EcologyPoolGetEnableJoinRankDaoPageVo();
                resultRecord.setDaoId(record.getId());
                resultRecord.setDaoName(record.getDaoName());
                resultRecords.add(resultRecord);
            });
        }
        return resultRecords;
    }

    @Override
    public List<EcologyPoolGetEnableJoinRankDaoPageVo> getEnableEcologyPools() {
        List<UserCreatorInfo> userCreatorInfoList = userCreatorInfoDao.getEnableEcologyPools();
        List<EcologyPoolGetEnableJoinRankDaoPageVo> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userCreatorInfoList)) {
            userCreatorInfoList.forEach(record -> {
                EcologyPoolGetEnableJoinRankDaoPageVo resultRecord = new EcologyPoolGetEnableJoinRankDaoPageVo();
                resultRecord.setDaoId(record.getId());
                resultRecord.setDaoName(record.getDaoName());
                resultRecords.add(resultRecord);
            });
        }
        return resultRecords;
    }

    @Override
    public Page<EcologyPoolCommunityServiceRankConfVO> communityServiceRankConfPage(Integer pageNo, Integer pageSize, String rankName) {
        Page<EcologyPoolCommunityServiceRankConf> page = ecologyPoolCommunityServiceRankConfDao.page(new Page<>(pageNo, pageSize), rankName, null, META_DAO_ID, null);
        Page<EcologyPoolCommunityServiceRankConfVO> resultPage = new Page<>();
        List<EcologyPoolCommunityServiceRankConfVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(record -> {
                EcologyPoolCommunityServiceRankConfVO resultRecord = new EcologyPoolCommunityServiceRankConfVO();
                resultRecord.setId(record.getId());
                resultRecord.setRankName(record.getRankName());
                resultRecord.setRankType(record.getRankType());
                resultRecord.setRankTypeName(record.getRankType().getDesc());
                resultRecord.setStartTime(record.getStartTime());
                resultRecord.setEndTime(record.getEndTime());
                resultRecord.setJoinRankCount(record.getJoinRankCount());
                resultRecord.setStatus(record.getStatus());
                resultRecords.add(resultRecord);
            });
        }
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        resultPage.setTotal(page.getTotal());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createCommunityServiceRankConf(EcologyPoolCreateCommunityServiceRankConfRequest request) {
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL_CREATE_COMMUNITY_SERVICE_RANK.getKey());
        try {
            if (!lock.tryLock(10, 10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            //检验
            validateCreateCommunityServiceRankConf(request);
            //执行
            doCreateCommunityServiceRankConf(request);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("创建排行榜异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Override
    public EcologyPoolMaxCommunityServiceRankEndTimeVo getMaxCommunityServiceRankEndTime(EcologyPoolMaxCommunityServiceRankEndTimeRequest request) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getMaxEndTime(request.getRankType(), request.getDaoId());
        Date maxEndTime = DateTime.now();
        if (Objects.nonNull(ecologyPoolCommunityServiceRankConf) && ecologyPoolCommunityServiceRankConf.getEndTime().after(maxEndTime)) {
            maxEndTime = ecologyPoolCommunityServiceRankConf.getEndTime();
        }
        EcologyPoolMaxCommunityServiceRankEndTimeVo ecologyPoolMaxCommunityServiceRankEndTimeVo = new EcologyPoolMaxCommunityServiceRankEndTimeVo();
        ecologyPoolMaxCommunityServiceRankEndTimeVo.setMaxEndTime(maxEndTime);
        return ecologyPoolMaxCommunityServiceRankEndTimeVo;
    }

    @Override
    public Boolean updateCommunityServiceRankConf(Long id, String activityRule, String topImage) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        Assert.notNull(ecologyPoolCommunityServiceRankConf, () -> new GlobalRunTimeException("排行榜不存在"));
        Assert.isFalse(ecologyPoolCommunityServiceRankConf.getStatus(), () -> new GlobalRunTimeException("排行榜已启用，不能编辑"));
        ecologyPoolCommunityServiceRankConf.setActivityRule(activityRule);
        ecologyPoolCommunityServiceRankConf.setTopImage(topImage);
        ecologyPoolCommunityServiceRankConf.updateById();
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateCommunityServiceRankConfStatus(Long id, Boolean status) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        Assert.notNull(ecologyPoolCommunityServiceRankConf, () -> new GlobalRunTimeException("排行榜不存在"));
        if (Objects.equals(ecologyPoolCommunityServiceRankConf.getStatus(), status)) {
            if (status) {
                throw new GlobalRunTimeException("排行榜已开启");
            } else {
                throw new GlobalRunTimeException("排行榜已关闭");
            }
        }
        ecologyPoolCommunityServiceRankConf.setStatus(status);
        ecologyPoolCommunityServiceRankConf.updateById();
        return Boolean.TRUE;
    }

    @Override
    public Boolean deleteCommunityServiceRankConf(Long id) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        Assert.notNull(ecologyPoolCommunityServiceRankConf, () -> new GlobalRunTimeException("排行榜不存在"));
        Assert.isFalse(ecologyPoolCommunityServiceRankConf.getStatus(), () -> new GlobalRunTimeException("排行榜已开启，不能删除"));
        Assert.isTrue(DateTime.now().before(ecologyPoolCommunityServiceRankConf.getStartTime()), () -> new GlobalRunTimeException("已到榜单开启时间，不能删除"));
        ecologyPoolCommunityServiceRankConf.deleteById();
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDaoCommunityServiceRankConf(Long id) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        Assert.notNull(ecologyPoolCommunityServiceRankConf, () -> new GlobalRunTimeException("排行榜不存在"));
        Assert.isFalse(ecologyPoolCommunityServiceRankConf.getStatus(), () -> new GlobalRunTimeException("排行榜已开启，不能删除"));
        Assert.isTrue(DateTime.now().before(ecologyPoolCommunityServiceRankConf.getStartTime()), () -> new GlobalRunTimeException("已到榜单开启时间，不能删除"));
        ecologyPoolCommunityServiceRankConf.deleteById();
        //region 回流积分
        EcologyPoolPrize totalEcologyPoolPrize = ecologyPoolPrizeDao.getPrizeById(ecologyPoolCommunityServiceRankConf.getId(), EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, EcologyPoolLinkTypeEnum.POINTS);
        BigDecimal totalPrize = Objects.nonNull(totalEcologyPoolPrize) ? totalEcologyPoolPrize.getLinkCount() : BigDecimal.ZERO;
        if (totalPrize.compareTo(BigDecimal.ZERO) > 0) {
            EcologyPoolIncreasePointsDTO ecologyPoolIncreasePointsDTO = EcologyPoolIncreasePointsDTO.builder()
                    .linkCount(totalPrize)
                    .linkType(EcologyPoolLinkTypeEnum.POINTS)
                    .poolType(EcologyPoolTypeEnum.BRAND)
                    .daoId(ecologyPoolCommunityServiceRankConf.getDaoId())
                    .operationType(EcologyPoolOperationTypeEnum.BACK_FLOW)
                    .sourcePoolType(Objects.equals(ecologyPoolCommunityServiceRankConf.getRankType(), EcologyPoolCommunityServiceRankTypeEnum.COMMUNITY) ? EcologyPoolTypeEnum.COMMUNITY_NETWORK_RANK : EcologyPoolTypeEnum.SERVICE_CENTER_RANK)
                    .sourceDaoId(ecologyPoolCommunityServiceRankConf.getDaoId())
                    .sourceRelationId(ecologyPoolCommunityServiceRankConf.getId())
                    .transactionUuid(IdUtil.simpleUUID())
                    .activeOperatorName("排行榜")
                    .passiveOperatorName("品牌生态池")
                    .build();
            this.increasePoints(ecologyPoolIncreasePointsDTO);
        }
        //endregion
        return Boolean.TRUE;
    }

    @Override
    public EcologyPoolCommunityServiceRankConfDetailVO communityServiceRankConfDetail(Long id) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        EcologyPoolCommunityServiceRankConfDetailVO ecologyPoolCommunityServiceRankConfDetailVO = new EcologyPoolCommunityServiceRankConfDetailVO();
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            return ecologyPoolCommunityServiceRankConfDetailVO;
        }
        ecologyPoolCommunityServiceRankConfDetailVO.setId(ecologyPoolCommunityServiceRankConf.getId());
        ecologyPoolCommunityServiceRankConfDetailVO.setRankName(ecologyPoolCommunityServiceRankConf.getRankName());
        ecologyPoolCommunityServiceRankConfDetailVO.setRankType(ecologyPoolCommunityServiceRankConf.getRankType());
        ecologyPoolCommunityServiceRankConfDetailVO.setNewUserCountThreshold(ecologyPoolCommunityServiceRankConf.getNewUserCountThreshold());
        ecologyPoolCommunityServiceRankConfDetailVO.setNewEcologySmeltingThreshold(ecologyPoolCommunityServiceRankConf.getNewEcologySmeltingThreshold());
        ecologyPoolCommunityServiceRankConfDetailVO.setStartTime(ecologyPoolCommunityServiceRankConf.getStartTime());
        ecologyPoolCommunityServiceRankConfDetailVO.setEndTime(ecologyPoolCommunityServiceRankConf.getEndTime());
        ecologyPoolCommunityServiceRankConfDetailVO.setActivityRule(ecologyPoolCommunityServiceRankConf.getActivityRule());
        ecologyPoolCommunityServiceRankConfDetailVO.setTopImage(ecologyPoolCommunityServiceRankConf.getTopImage());
        ecologyPoolCommunityServiceRankConfDetailVO.setStatus(ecologyPoolCommunityServiceRankConf.getStatus());

        //填充榜单收益
        List<EcologyPoolCommunityServiceRankIncomeConf> incomeList = ecologyPoolCommunityServiceRankIncomeConfDao.getListByConfId(id);
        if (CollectionUtil.isNotEmpty(incomeList)) {
            //填充榜单收益条件
            List<EcologyPoolCommunityServiceRankIncomeConditionConf> conditionList = ecologyPoolCommunityServiceRankIncomeConditionConfDao.getListByConfId(id);
            Map<Long, EcologyPoolCommunityServiceRankIncomeConditionConf> conditionMap = CollectionUtil.isNotEmpty(conditionList) ? conditionList.stream().collect(Collectors.toMap(EcologyPoolCommunityServiceRankIncomeConditionConf::getEcologyPoolCommunityServiceRankIncomeConfId, Function.identity())) : new HashMap<>();
            List<EcologyPoolCommunityServiceRankConfDetailIncomeVO> ecologyPoolCommunityServiceRankConfDetailIncomeVOList = new ArrayList<>();
            for (EcologyPoolCommunityServiceRankIncomeConf income : incomeList) {
                //region 填充榜单收益
                EcologyPoolCommunityServiceRankConfDetailIncomeVO ecologyPoolCommunityServiceRankConfDetailIncomeVO = new EcologyPoolCommunityServiceRankConfDetailIncomeVO();
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setSort(income.getSort());
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setIncomeName(income.getIncomeName());
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setStartRank(income.getStartRank());
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setEndRank(income.getEndRank());
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setPrizeRatio(income.getPrizeRatio());
                EcologyPoolCommunityServiceRankIncomeConditionConf condition = conditionMap.get(income.getId());
                if (Objects.nonNull(condition)) {
                    //region 填充榜单收益条件
                    EcologyPoolCommunityServiceRankConfDetailIncomeConditionVO communityServiceRankConfDetailIncomeConditionVO = new EcologyPoolCommunityServiceRankConfDetailIncomeConditionVO();
                    communityServiceRankConfDetailIncomeConditionVO.setNewEcologySmeltingThreshold(condition.getNewEcologySmeltingThreshold());
                    communityServiceRankConfDetailIncomeConditionVO.setNewUserCountThreshold(condition.getNewUserCountThreshold());
                    ecologyPoolCommunityServiceRankConfDetailIncomeVO.setCondition(communityServiceRankConfDetailIncomeConditionVO);
                    //endregion
                }
                ecologyPoolCommunityServiceRankConfDetailIncomeVOList.add(ecologyPoolCommunityServiceRankConfDetailIncomeVO);
                //endregion
            }
            ecologyPoolCommunityServiceRankConfDetailVO.setIncomeList(ecologyPoolCommunityServiceRankConfDetailIncomeVOList);
        }

        //region 填充关联
        List<EcologyPoolRelationConditionBind> ecologyPoolRelationConditionBindList = ecologyPoolRelationConditionBindDao.getListByBind(ecologyPoolCommunityServiceRankConf.getId(), EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, EcologyPoolRelationTypeEnum.COLLECTION);
        if (CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList)) {
            List<EcologyPoolDaoCommunityServiceRankConfDetailRelationVO> ecologyPoolDaoCommunityServiceRankConfDetailRelationVOList = new ArrayList<>();
            ecologyPoolRelationConditionBindList.forEach(bind -> {
                EcologyPoolDaoCommunityServiceRankConfDetailRelationVO ecologyPoolDaoCommunityServiceRankConfDetailRelationVO = new EcologyPoolDaoCommunityServiceRankConfDetailRelationVO();
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVO.setRelationType(bind.getRelationType());
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVO.setRelationId(bind.getRelationId());
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVOList.add(ecologyPoolDaoCommunityServiceRankConfDetailRelationVO);
            });
            ecologyPoolCommunityServiceRankConfDetailVO.setRelationList(ecologyPoolDaoCommunityServiceRankConfDetailRelationVOList);
        }
        //endregion
        ecologyPoolCommunityServiceRankConfDetailVO.setAllRelation(CollectionUtil.isEmpty(ecologyPoolCommunityServiceRankConfDetailVO.getRelationList()));
        return ecologyPoolCommunityServiceRankConfDetailVO;
    }

    @Override
    public Page<EcologyPoolCommunityServiceRankVO> communityServiceRankPage(Integer pageNo, Integer pageSize, Long id) {
        //获取最大日期，然后再根据最大日期查询榜单数据
        EcologyPoolCommunityServiceRank ecologyPoolCommunityServiceRank = ecologyPoolCommunityServiceRankDao.getMaxRankDate(id);
        if (Objects.isNull(ecologyPoolCommunityServiceRank)) {
            return new Page<>(pageNo, pageSize);
        }
        Page<EcologyPoolCommunityServiceRank> page = ecologyPoolCommunityServiceRankDao.showPage(new Page<>(pageNo, pageSize), id, ecologyPoolCommunityServiceRank.getRankDate());
        Page<EcologyPoolCommunityServiceRankVO> resultPage = new Page<>();
        List<EcologyPoolCommunityServiceRankVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<Long> userIdList = page.getRecords().stream().map(EcologyPoolCommunityServiceRank::getUserId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            List<UserInfo> userInfoList = CollectionUtil.isNotEmpty(userIdList) ? userInfoDao.getByIdList(userIdList) : new ArrayList<>();
            Map<Long, UserInfo> userInfoMap = CollectionUtil.isNotEmpty(userInfoList) ? userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity())) : new HashMap<>();
            page.getRecords().forEach(record -> {
                EcologyPoolCommunityServiceRankVO resultRecord = new EcologyPoolCommunityServiceRankVO();
                resultRecord.setSort(record.getSort());
                resultRecord.setSortChange(record.getSortChange());
                resultRecord.setDaoId(record.getDaoId());
                resultRecord.setRankName(record.getRankName());
                resultRecord.setPrizeRatio(record.getPrizeRatio());
                resultRecord.setNewUserCount(record.getNewUserCount());
                resultRecord.setNewEcologySmelting(record.getNewEcologySmelting());
                resultRecord.setUserId(record.getUserId());
                if (Objects.nonNull(record.getUserId()) && Objects.nonNull(userInfoMap.get(record.getUserId()))) {
                    UserInfo userInfo = userInfoMap.get(record.getUserId());
                    resultRecord.setUserTel(userInfo.getUserTel());
                    resultRecord.setNickName(userInfo.getNickName());
                }
                resultRecords.add(resultRecord);
            });
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    public Page<EcologyPoolDaoCommunityServiceRankVO> daoCommunityServiceRankPage(Integer pageNo, Integer pageSize, Long id) {
        //查询榜单，获取品牌id
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            return new Page<>(pageNo, pageSize);
        }
        //获取最大日期，然后再根据最大日期查询榜单数据
        EcologyPoolCommunityServiceRank ecologyPoolCommunityServiceRank = ecologyPoolCommunityServiceRankDao.getMaxRankDate(id);
        if (Objects.isNull(ecologyPoolCommunityServiceRank)) {
            return new Page<>(pageNo, pageSize);
        }
        EcologyPool ecologyPool = Objects.nonNull(ecologyPoolCommunityServiceRank.getDaoId()) ? ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, ecologyPoolCommunityServiceRankConf.getDaoId()) : null;
        Page<EcologyPoolCommunityServiceRank> page = ecologyPoolCommunityServiceRankDao.showPage(new Page<>(pageNo, pageSize), id, ecologyPoolCommunityServiceRank.getRankDate());
        Page<EcologyPoolDaoCommunityServiceRankVO> resultPage = new Page<>();
        List<EcologyPoolDaoCommunityServiceRankVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            //region 账号信息
            List<Long> userIdList = page.getRecords().stream().map(EcologyPoolCommunityServiceRank::getUserId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            List<UserInfo> userInfoList = CollectionUtil.isNotEmpty(userIdList) ? userInfoDao.getByIdList(userIdList) : new ArrayList<>();
            Map<Long, UserInfo> userInfoMap = CollectionUtil.isNotEmpty(userInfoList) ? userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity())) : new HashMap<>();
            //endregion
            //region 奖励
            List<EcologyPoolCommunityServiceRankIncomeConf> incomeList = ecologyPoolCommunityServiceRankIncomeConfDao.getListByConfId(id);
            List<Long> incomeIdList = CollectionUtil.isNotEmpty(incomeList) ? incomeList.stream().map(EcologyPoolCommunityServiceRankIncomeConf::getId).collect(Collectors.toList()) : new ArrayList<>();
            List<EcologyPoolPrize> ecologyPoolPrizeList = CollectionUtil.isNotEmpty(incomeIdList) ? ecologyPoolPrizeDao.listPrizeById(incomeIdList, EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK_INCOME, null) : new ArrayList<>();
            Map<Long, List<EcologyPoolPrize>> ecologyPoolPrizeMap = CollectionUtil.isNotEmpty(ecologyPoolPrizeList) ? ecologyPoolPrizeList.stream().collect(Collectors.groupingBy(EcologyPoolPrize::getBindId)) : new HashMap<>();
            //endregion
            page.getRecords().forEach(record -> {
                EcologyPoolDaoCommunityServiceRankVO resultRecord = new EcologyPoolDaoCommunityServiceRankVO();
                resultRecord.setSort(record.getSort());
                resultRecord.setDaoId(record.getDaoId());
                resultRecord.setRankName(record.getRankName());
                //region 奖励
                String prize = "";
                if (record.getHasSort() && Objects.nonNull(record.getSort()) && CollectionUtil.isNotEmpty(incomeList)) {
                    for (EcologyPoolCommunityServiceRankIncomeConf incomeConf : incomeList) {
                        if (record.getSort() > incomeConf.getStartRank() && record.getSort() <= incomeConf.getEndRank()) {
                            List<EcologyPoolPrize> prizeList = ecologyPoolPrizeMap.get(incomeConf.getId());
                            if (CollectionUtil.isNotEmpty(prizeList)) {
                                prize = prizeList.stream().map(v -> {
                                    if (Objects.equals(v.getLinkType(), EcologyPoolLinkTypeEnum.POINTS)
                                            && Objects.nonNull(ecologyPool) && StrUtil.isNotBlank(ecologyPool.getPoolName())) {
                                        return ecologyPool.getPoolName() + "*" + v.getLinkCount();
                                    }
                                    return v.getLinkType().getDesc() + "*" + v.getLinkCount();
                                }).collect(Collectors.joining(","));
                            }
                        }
                    }
                }
                resultRecord.setPrize(prize);
                //endregion
                resultRecord.setNewUserCount(record.getNewUserCount());
                resultRecord.setNewEcologySmelting(record.getNewEcologySmelting());
                if (Objects.nonNull(record.getUserId()) && Objects.nonNull(userInfoMap.get(record.getUserId()))) {
                    UserInfo userInfo = userInfoMap.get(record.getUserId());
                    resultRecord.setUserTel(userInfo.getUserTel());
                    resultRecord.setNickName(userInfo.getNickName());
                }
                resultRecords.add(resultRecord);
            });
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    public Page<EcologyPoolRecordRpcVO> recordPage(Integer pageNo, Integer pageSize, String userTel, List<EcologyPoolTypeEnum> poolTypeList, EcologyPoolFlowTypeEnum flowType, Date startTime, Date endTime, Long daoId) {
        if (CollectionUtils.isEmpty(poolTypeList)) {
            throw new GlobalRunTimeException("生态池不能为空");
        }
        Long userId = null;
        if (StrUtil.isNotBlank(userTel)) {
            UserInfo userInfo = userInfoDao.getByUserTel(userTel);
            if (Objects.isNull(userInfo)) {
                return new Page<>(pageNo, pageSize);
            }
            userId = userInfo.getId();
        }
        Page<EcologyPoolRecord> page = ecologyPoolRecordDao.recordPage(new Page<>(pageNo, pageSize), poolTypeList, flowType, startTime, endTime, daoId, userId);
        List<EcologyPoolRecord> records = page.getRecords();
        List<EcologyPoolRecordRpcVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(record -> {
                EcologyPoolRecordRpcVO resultRecord = new EcologyPoolRecordRpcVO();
                resultRecord.setCreateTime(record.getCreateTime());
                resultRecord.setFlowType(record.getFlowType());
                resultRecord.setLinkType(record.getLinkType());
                resultRecord.setLinkTypeName(record.getLinkType().getDesc());
                resultRecord.setLinkCount(record.getLinkCount());
                resultRecord.setAfterLinkCount(record.getAfterLinkCount());
                resultRecord.setSourcePoolType(record.getSourcePoolType());
                resultRecord.setSourcePoolTypeName(record.getPassiveOperatorName());
                resultRecord.setPoolType(record.getPoolType());
                resultRecord.setPoolTypeName(record.getActiveOperatorName());
                resultRecord.setOperationType(record.getOperationType());
                resultRecord.setOperationTypeName(record.getOperationType().getDesc());
                resultRecord.setRemark(record.getRemark());
                resultRecords.add(resultRecord);
            });
        }
        Page<EcologyPoolRecordRpcVO> resultPage = new Page<>();
        resultPage.setCurrent(page.getCurrent());
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    public Map<EcologyPoolTypeEnum, EcologyPoolDataVO> getPoolData(List<EcologyPoolTypeEnum> typeList, Long daoId, UserInfo userInfo) {
        if (CollectionUtil.isEmpty(typeList)) {
            throw new GlobalRunTimeException("类型不能为空");
        }
        Map<EcologyPoolTypeEnum, EcologyPoolDataVO> ecologyPoolDataVOMap = new HashMap<>();
        //region 单独处理品牌池
        if (typeList.contains(EcologyPoolTypeEnum.BRAND)) {
            if (Objects.isNull(daoId)) {
                throw new GlobalRunTimeException("品牌ID不能为空");
            }
            EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, daoId);
            EcologyPoolDataVO ecologyPoolDataVO = new EcologyPoolDataVO();
            ecologyPoolDataVO.setType(EcologyPoolTypeEnum.BRAND);
            if (Objects.nonNull(ecologyPool)) {
                ecologyPoolDataVO.setId(ecologyPool.getId());
                ecologyPoolDataVO.setLinkCount(ecologyPool.getLinkCount());
                ecologyPoolDataVO.setLinkType(ecologyPool.getLinkType());
                ecologyPoolDataVO.setLinkTypeName(ecologyPool.getLinkType().getDesc());
                ecologyPoolDataVO.setPoolName(StrUtil.isNotBlank(ecologyPool.getPoolName()) ? ecologyPool.getPoolName() : ecologyPool.getLinkType().getDesc());
            }
            ecologyPoolDataVOMap.put(EcologyPoolTypeEnum.BRAND, ecologyPoolDataVO);
            typeList = typeList.stream().filter(type -> !Objects.equals(type.getCode(), EcologyPoolTypeEnum.BRAND.getCode())).collect(Collectors.toList());
        }
        //endregion
        //region 单独处理账号
        if (typeList.contains(EcologyPoolTypeEnum.ACCOUNT)) {
            if (Objects.isNull(userInfo)) {
                throw new GlobalRunTimeException("账号不能为空");
            }
            EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoIdUserId(EcologyPoolTypeEnum.ACCOUNT, EcologyPoolLinkTypeEnum.POINTS, daoId, userInfo.getId());
            EcologyPoolDataVO ecologyPoolDataVO = new EcologyPoolDataVO();
            ecologyPoolDataVO.setType(EcologyPoolTypeEnum.ACCOUNT);
            if (Objects.nonNull(ecologyPool)) {
                ecologyPoolDataVO.setId(ecologyPool.getId());
                ecologyPoolDataVO.setLinkCount(ecologyPool.getLinkCount());
                ecologyPoolDataVO.setLinkType(ecologyPool.getLinkType());
                ecologyPoolDataVO.setLinkTypeName(ecologyPool.getLinkType().getDesc());
                ecologyPoolDataVO.setPoolName(StrUtil.isNotBlank(ecologyPool.getPoolName()) ? ecologyPool.getPoolName() : ecologyPool.getLinkType().getDesc());
            }
            ecologyPoolDataVOMap.put(EcologyPoolTypeEnum.ACCOUNT, ecologyPoolDataVO);
            typeList = typeList.stream().filter(type -> !Objects.equals(type.getCode(), EcologyPoolTypeEnum.ACCOUNT.getCode())).collect(Collectors.toList());
        }
        //endregion
        if (CollectionUtil.isEmpty(typeList)) {
            return ecologyPoolDataVOMap;
        }
        //region 查询积分
        List<EcologyPool> ecologyPoolList = ecologyPoolDao.getListByTypes(typeList, EcologyPoolLinkTypeEnum.POINTS, daoId);
        //endregion
        //region 组装返回值
        Map<EcologyPoolTypeEnum, EcologyPool> ecologyPoolMap = CollectionUtil.isNotEmpty(ecologyPoolList) ? ecologyPoolList.stream().collect(Collectors.toMap(EcologyPool::getPoolType, Function.identity())) : Maps.newHashMap();
        typeList.forEach(type -> {
            EcologyPoolDataVO ecologyPoolDataVO = new EcologyPoolDataVO();
            ecologyPoolDataVO.setType(type);
            EcologyPool ecologyPool = ecologyPoolMap.get(type);
            if (Objects.nonNull(ecologyPool)) {
                ecologyPoolDataVO.setId(ecologyPool.getId());
                ecologyPoolDataVO.setLinkCount(ecologyPool.getLinkCount().setScale(2, RoundingMode.HALF_UP));
                ecologyPoolDataVO.setLinkType(ecologyPool.getLinkType());
                ecologyPoolDataVO.setLinkTypeName(ecologyPool.getLinkType().getDesc());
                ecologyPoolDataVO.setPoolName(StrUtil.isNotBlank(ecologyPool.getPoolName()) ? ecologyPool.getPoolName() : ecologyPool.getLinkType().getDesc());
            }
            ecologyPoolDataVOMap.put(type, ecologyPoolDataVO);
        });
        //endregion
        return ecologyPoolDataVOMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean communityServiceCenterAllocatePoints(EcologyPoolOperationTypeEnum operationType, EcologyPoolTypeEnum poolType, Long userId, Long linkCount, EcologyPoolLinkTypeEnum linkType, String remark) {
        if (!Objects.equals(poolType.getCode(), EcologyPoolTypeEnum.SERVICE_CENTER.getCode())
                && !Objects.equals(poolType.getCode(), EcologyPoolTypeEnum.COMMUNITY_NETWORK.getCode())) {
            throw new GlobalRunTimeException("目前仅支持服务中心池和社区网点池");
        }
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL_ALLOCATE.getKey());
        try {
            if (!lock.tryLock(10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            //校验
            List<EcologyPool> ecologyPoolList = validateCommunityServiceCenterAllocatePoints(operationType, poolType, userId, linkCount, linkType);
            //执行
            doCommunityServiceCenterAllocatePoints(ecologyPoolList, operationType, poolType, userId, linkCount, linkType, remark);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("官方生态池分配/扣除积分异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchCommunityServiceCenterAllocatePoints(EcologyPoolBatchAllocatePointsRequest request) {
        if (!Objects.equals(request.getPoolType().getCode(), EcologyPoolTypeEnum.SERVICE_CENTER.getCode())
                && !Objects.equals(request.getPoolType().getCode(), EcologyPoolTypeEnum.COMMUNITY_NETWORK.getCode())) {
            throw new GlobalRunTimeException("目前仅支持服务中心池和社区网点池");
        }
        if (CollectionUtil.isEmpty(request.getUserList())) {
            throw new GlobalRunTimeException("用户列表不能为空");
        }
        request.getUserList().forEach(user -> {
            Assert.notNull(user.getUserId(), () -> new GlobalRunTimeException("用户id不能为空"));
            Assert.notNull(user.getLinkCount(), () -> new GlobalRunTimeException("积分不能为空"));
            Assert.isTrue(user.getLinkCount() >= 0, () -> new GlobalRunTimeException("积分不能小于0"));
        });
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL_ALLOCATE.getKey());
        try {
            if (!lock.tryLock(10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            request.getUserList().forEach(user -> {
                if (user.getLinkCount() > 0) {
                    //校验
                    List<EcologyPool> ecologyPoolList = validateCommunityServiceCenterAllocatePoints(request.getOperationType(), request.getPoolType(), user.getUserId(), user.getLinkCount(), request.getLinkType());
                    //执行
                    doCommunityServiceCenterAllocatePoints(ecologyPoolList, request.getOperationType(), request.getPoolType(), user.getUserId(), user.getLinkCount(), request.getLinkType(), request.getRemark());
                }
            });
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("官方生态池分配/扣除积分异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Override
    public EcologyPoolFindPointsByUserTelVO findPointsByUserTel(Long daoId, String userTel, EcologyPoolLinkTypeEnum linkType, EcologyPoolTypeEnum poolType) {
        UserInfo userInfo = userInfoDao.getOneByUserTel(userTel);
        Assert.notNull(userInfo, () -> new GlobalRunTimeException("账号不存在"));
        EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoIdUserId(EcologyPoolTypeEnum.ACCOUNT, linkType, daoId, userInfo.getId());
        Boolean popWindow = Boolean.FALSE;
        if (Objects.nonNull(poolType)) {
            if (Objects.equals(poolType.getCode(), EcologyPoolTypeEnum.SERVICE_CENTER.getCode())) {
                UserCityServerCentre userCityServerCentre = userCityServerCentreDao.selectByUserId(userInfo.getId());
                if (Objects.isNull(userCityServerCentre)) {
                    popWindow = Boolean.TRUE;
                }
            } else if (Objects.equals(poolType.getCode(), EcologyPoolTypeEnum.COMMUNITY_NETWORK.getCode())) {
                UserWorkRoom userWorkRoom = userWorkRoomDao.selectByUserId(userInfo.getId());
                if (Objects.isNull(userWorkRoom)) {
                    popWindow = Boolean.TRUE;
                }
            }
        }
        EcologyPoolFindPointsByUserTelVO ecologyPoolFindPointsByUserTelVO = new EcologyPoolFindPointsByUserTelVO();
        ecologyPoolFindPointsByUserTelVO.setUserId(userInfo.getId());
        ecologyPoolFindPointsByUserTelVO.setUserTel(userInfo.getUserTel());
        ecologyPoolFindPointsByUserTelVO.setNickName(userInfo.getNickName());
        if (Objects.nonNull(ecologyPool)) {
            ecologyPoolFindPointsByUserTelVO.setCurrentLinkCount(ecologyPool.getLinkCount());
        }
        ecologyPoolFindPointsByUserTelVO.setLinkType(linkType);
        ecologyPoolFindPointsByUserTelVO.setLinkTypeName(linkType.getDesc());
        ecologyPoolFindPointsByUserTelVO.setPopWindow(popWindow);
        return ecologyPoolFindPointsByUserTelVO;
    }

    @Override
    public EcologyPoolUserUploadVo findPointsByUserTelList(Long daoId, EcologyPoolLinkTypeEnum linkType, List<EcologyPoolUploadUserDataRpcRequest> dataList, EcologyPoolTypeEnum poolType) {
        //region 校验手机号是否存在
        Map<String, List<EcologyPoolUploadUserDataRpcRequest>> dataMap = dataList.stream().collect(Collectors.groupingBy(EcologyPoolUploadUserDataRpcRequest::getUserTel));
        List<UserInfo> userInfoList = userInfoDao.getUserInfoList(new ArrayList<>(dataMap.keySet()));
        Map<String, List<UserInfo>> userInfoMap = CollectionUtil.isNotEmpty(userInfoList) ? userInfoList.stream().collect(Collectors.groupingBy(UserInfo::getUserTel)) : new HashMap<>();
        dataMap.forEach((key, value) -> {
            if (CollectionUtil.isEmpty(userInfoMap.get(key))) {
                throw new GlobalRunTimeException("手机号码" + key + "不存在");
            }
        });
        //endregion
        //region 判断是否弹窗提示
        Boolean popWindow = Boolean.FALSE;
        List<EcologyPoolUserUploadDataVo> ecologyPoolUserUploadDataVoList = new ArrayList<>();
        List<Long> userIdList = userInfoList.stream().map(UserInfo::getId).collect(Collectors.toList());
        if (Objects.nonNull(poolType)) {
            if (Objects.equals(poolType.getCode(), EcologyPoolTypeEnum.SERVICE_CENTER.getCode())) {
                List<UserCityServerCentre> userCityServerCentreList = userCityServerCentreDao.selectByUserIdList(userIdList);
                if (CollectionUtil.isEmpty(userCityServerCentreList) || userCityServerCentreList.size() < userIdList.size()) {
                    popWindow = Boolean.TRUE;
                }
            } else if (Objects.equals(poolType.getCode(), EcologyPoolTypeEnum.COMMUNITY_NETWORK.getCode())) {
                List<UserWorkRoom> userWorkRoomList = userWorkRoomDao.selectByUserIdList(userIdList);
                if (CollectionUtil.isEmpty(userIdList) || userWorkRoomList.size() < userIdList.size()) {
                    popWindow = Boolean.TRUE;
                }
            }
        }
        //endregion
        //region 查询账号积分
        List<EcologyPool> ecologyPoolList = ecologyPoolDao.getByTypeAndDaoIdUserIdList(EcologyPoolTypeEnum.ACCOUNT, linkType, daoId, userIdList);
        //endregion
        //region 组装返回值
        Map<Long, EcologyPool> ecologyPoolMap = CollectionUtil.isNotEmpty(ecologyPoolList) ? ecologyPoolList.stream().collect(Collectors.toMap(EcologyPool::getUserId, Function.identity())) : new HashMap<>();
        userInfoList.forEach(userInfo -> {
            EcologyPoolUserUploadDataVo ecologyPoolUserUploadDataVo = new EcologyPoolUserUploadDataVo();
            ecologyPoolUserUploadDataVo.setUserId(userInfo.getId());
            ecologyPoolUserUploadDataVo.setUserTel(userInfo.getUserTel());
            ecologyPoolUserUploadDataVo.setNickName(userInfo.getNickName());
            ecologyPoolUserUploadDataVo.setLinkType(linkType);
            ecologyPoolUserUploadDataVo.setLinkTypeName(linkType.getDesc());
            //region 分配积分
            Long linkCount = 0L;
            List<EcologyPoolUploadUserDataRpcRequest> ecologyPoolUploadUserDataRpcRequests = dataMap.get(userInfo.getUserTel());
            if (CollectionUtil.isNotEmpty(ecologyPoolUploadUserDataRpcRequests)) {
                linkCount = ecologyPoolUploadUserDataRpcRequests.get(0).getLinkCount();
            }
            ecologyPoolUserUploadDataVo.setLinkCount(linkCount);
            //endregion
            //region 当前存在积分
            BigDecimal currentLinkCount = BigDecimal.ZERO;
            EcologyPool ecologyPool = ecologyPoolMap.get(userInfo.getId());
            if (Objects.nonNull(ecologyPool)) {
                currentLinkCount = ecologyPool.getLinkCount();
            }
            ecologyPoolUserUploadDataVo.setCurrentLinkCount(currentLinkCount);
            //endregion
            ecologyPoolUserUploadDataVoList.add(ecologyPoolUserUploadDataVo);
        });
        EcologyPoolUserUploadVo ecologyPoolUserUploadVo = new EcologyPoolUserUploadVo();
        ecologyPoolUserUploadVo.setTotalCount(dataList.size());
        ecologyPoolUserUploadVo.setSuccessCount(CollectionUtil.isNotEmpty(userInfoList) ? userInfoList.size() : 0);
        ecologyPoolUserUploadVo.setUserList(ecologyPoolUserUploadDataVoList);
        ecologyPoolUserUploadVo.setPopWindow(popWindow);
        //endregion
        return ecologyPoolUserUploadVo;
    }

    @Override
    public EcologyPoolWebRankConfVO daoRankConf() {
        EcologyPoolDaoRankConf ecologyPoolDaoRankConf = ecologyPoolDaoRankConfDao.getLastActive();
        EcologyPoolWebRankConfVO ecologyPoolWebRankConfVO = new EcologyPoolWebRankConfVO();
        if (Objects.nonNull(ecologyPoolDaoRankConf)) {
            if (ecologyPoolDaoRankConf.getEndTime().before(DateTime.now())) {
                ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.NOTHING);
            } else {
                ecologyPoolWebRankConfVO.setStartTime(ecologyPoolDaoRankConf.getStartTime());
                ecologyPoolWebRankConfVO.setEndTime(ecologyPoolDaoRankConf.getEndTime());
                ecologyPoolWebRankConfVO.setActivityRule(ecologyPoolDaoRankConf.getActivityRule());
                ecologyPoolWebRankConfVO.setTopImage(ecologyPoolDaoRankConf.getTopImage());
                if (ecologyPoolDaoRankConf.getStartTime().before(DateTime.now())) {
                    ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.STARTED);
                } else {
                    ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.NOT_START);
                }
                ecologyPoolWebRankConfVO.setRankName(ecologyPoolDaoRankConf.getRankName());
            }
        } else {
            ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.NOTHING);
        }
        return ecologyPoolWebRankConfVO;
    }

    @Override
    public EcologyPoolHistoryDaoRankConfVo historyDaoRankConfDetail(Long id) {
        EcologyPoolDaoRankConf ecologyPoolDaoRankConf = ecologyPoolDaoRankConfDao.getById(id);
        if (Objects.isNull(ecologyPoolDaoRankConf)) {
            throw new GlobalRunTimeException("排行榜不存在");
        }
        EcologyPoolHistoryDaoRankConfVo ecologyPoolHistoryDaoRankConfVo = new EcologyPoolHistoryDaoRankConfVo();
        ecologyPoolHistoryDaoRankConfVo.setId(ecologyPoolDaoRankConf.getId());
        ecologyPoolHistoryDaoRankConfVo.setStartTime(ecologyPoolDaoRankConf.getStartTime());
        ecologyPoolHistoryDaoRankConfVo.setEndTime(ecologyPoolDaoRankConf.getEndTime());
        ecologyPoolHistoryDaoRankConfVo.setActivityRule(ecologyPoolDaoRankConf.getActivityRule());
        ecologyPoolHistoryDaoRankConfVo.setTopImage(ecologyPoolDaoRankConf.getTopImage());
        ecologyPoolHistoryDaoRankConfVo.setRankName(ecologyPoolDaoRankConf.getRankName());
        return ecologyPoolHistoryDaoRankConfVo;
    }

    @Override
    public IPage<EcologyPoolWebDaoRankVO> daoRankPage(Integer pageNo, Integer pageSize) {
        EcologyPoolDaoRankConf ecologyPoolDaoRankConf = ecologyPoolDaoRankConfDao.getLastActive();
        if (Objects.isNull(ecologyPoolDaoRankConf)) {
            return new Page<>(pageNo, pageSize);
        }
        if (!ecologyPoolDaoRankConf.getStartTime().before(DateTime.now())) {
            return new Page<>(pageNo, pageSize);
        }
        EcologyPoolDaoRank ecologyPoolDaoRank = ecologyPoolDaoRankDao.getMaxRankDate(ecologyPoolDaoRankConf.getId());
        if (Objects.isNull(ecologyPoolDaoRank)) {
            return new Page<>(pageNo, pageSize);
        }
        return ecologyPoolDaoRankDao.showPage(new Page<>(pageNo, pageSize), ecologyPoolDaoRankConf.getId(), ecologyPoolDaoRank.getRankDate()).convert(record -> {
            EcologyPoolWebDaoRankVO resultRecord = new EcologyPoolWebDaoRankVO();
            resultRecord.setHasSort(record.getHasSort());
            resultRecord.setSort(record.getSort());
            int sortChange = Objects.nonNull(record.getSortChange()) ? record.getSortChange() : 0;
            EcologyPoolDaoRankSortChangeSignEnum sortChangeSign = sortChange > 0 ? EcologyPoolDaoRankSortChangeSignEnum.DECLINE : (sortChange < 0 ? EcologyPoolDaoRankSortChangeSignEnum.RISE : EcologyPoolDaoRankSortChangeSignEnum.UNCHANGED);
            resultRecord.setSortChange(sortChange);
            resultRecord.setSortChangeSign(sortChangeSign);
            resultRecord.setRankName(record.getRankName());
            resultRecord.setContribution(record.getContribution().setScale(2, RoundingMode.HALF_UP).toPlainString());
            return resultRecord;
        });
    }

    @Override
    public Page<EcologyPoolWebRecordVO> webRecordPage(Integer pageNo, Integer pageSize, EcologyPoolTypeEnum poolType, Long daoId, UserInfo userInfo) {
        Long userId = null;
        EcologyPool ecologyPool = null;
        if (Objects.equals(poolType.getCode(), EcologyPoolTypeEnum.ACCOUNT.getCode())) {
            userId = userInfo.getId();
            if (Objects.nonNull(daoId)) {
                ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, daoId);
            }
        }
        Page<EcologyPoolRecord> page = ecologyPoolRecordDao.recordPage(new Page<>(pageNo, pageSize), poolType, daoId, userId);
        Page<EcologyPoolWebRecordVO> resultPage = new Page<>();
        List<EcologyPoolWebRecordVO> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            for (EcologyPoolRecord record : page.getRecords()) {
                EcologyPoolWebRecordVO resultRecord = new EcologyPoolWebRecordVO();
                resultRecord.setCreateTime(record.getCreateTime());
                resultRecord.setSourcePoolType(record.getSourcePoolType());
                resultRecord.setSourcePoolTypeName(record.getSourcePoolType().getDesc());
                resultRecord.setSourceDaoId(record.getSourceDaoId());
                resultRecord.setSourceDaoName(record.getPassiveOperatorName());
                resultRecord.setFlowType(record.getFlowType());
                resultRecord.setFlowTypeName(record.getFlowType().getDesc());
                resultRecord.setOperationType(record.getOperationType());
                resultRecord.setOperationTypeName(record.getOperationType().getDesc());
                resultRecord.setLinkCount(record.getLinkCount());
                resultRecord.setLinkType(record.getLinkType());
                resultRecord.setLinkTypeName(record.getLinkType().getDesc());
                if (Objects.equals(record.getLinkType(), EcologyPoolLinkTypeEnum.POINTS)
                        && Objects.nonNull(ecologyPool)
                        && StrUtil.isNotBlank(ecologyPool.getPoolName())) {
                    resultRecord.setLinkTypeName(ecologyPool.getPoolName());
                }
                resultRecords.add(resultRecord);
            }
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    public IPage<EcologyPoolWebHistoryDaoRankConfVO> historyDaoRankConfPage(Integer pageNo, Integer pageSize) {
        return ecologyPoolDaoRankConfDao.historyDaoRankPage(pageNo, pageSize).convert(page -> {
            EcologyPoolWebHistoryDaoRankConfVO ecologyPoolWebHistoryDaoRankConfVO = new EcologyPoolWebHistoryDaoRankConfVO();
            ecologyPoolWebHistoryDaoRankConfVO.setId(page.getId());
            ecologyPoolWebHistoryDaoRankConfVO.setRankName(page.getRankName());
            ecologyPoolWebHistoryDaoRankConfVO.setStartTime(page.getStartTime());
            ecologyPoolWebHistoryDaoRankConfVO.setEndTime(page.getEndTime());
            return ecologyPoolWebHistoryDaoRankConfVO;
        });
    }

    @Override
    public IPage<EcologyPoolWebHistoryRankVO> historyDaoRankPage(Integer pageNo, Integer pageSize, Long id) {
        EcologyPoolDaoRankConf ecologyPoolDaoRankConf = ecologyPoolDaoRankConfDao.getById(id);
        if (Objects.isNull(ecologyPoolDaoRankConf)) {
            return new Page<>(pageNo, pageSize);
        }
        EcologyPoolDaoRank ecologyPoolDaoRank = ecologyPoolDaoRankDao.getMaxRankDate(ecologyPoolDaoRankConf.getId());
        if (Objects.isNull(ecologyPoolDaoRank)) {
            return new Page<>(pageNo, pageSize);
        }
        return ecologyPoolDaoRankDao.showPage(new Page<>(pageNo, pageSize), ecologyPoolDaoRankConf.getId(), ecologyPoolDaoRank.getRankDate()).convert(page -> {
            EcologyPoolWebHistoryRankVO ecologyPoolWebHistoryDaoRankVO = new EcologyPoolWebHistoryRankVO();
            ecologyPoolWebHistoryDaoRankVO.setHasSort(page.getHasSort());
            ecologyPoolWebHistoryDaoRankVO.setSort(page.getSort());
            int sortChange = Objects.nonNull(page.getSortChange()) ? page.getSortChange() : 0;
            EcologyPoolDaoRankSortChangeSignEnum sortChangeSign = sortChange > 0 ? EcologyPoolDaoRankSortChangeSignEnum.DECLINE : (sortChange < 0 ? EcologyPoolDaoRankSortChangeSignEnum.RISE : EcologyPoolDaoRankSortChangeSignEnum.UNCHANGED);
            ecologyPoolWebHistoryDaoRankVO.setSortChange(sortChange);
            ecologyPoolWebHistoryDaoRankVO.setSortChangeSign(sortChangeSign);
            ecologyPoolWebHistoryDaoRankVO.setRankName(page.getRankName());
            ecologyPoolWebHistoryDaoRankVO.setContribution(page.getContribution().setScale(2, RoundingMode.HALF_UP).toPlainString());
            return ecologyPoolWebHistoryDaoRankVO;
        });
    }

    @Override
    public EcologyPoolWebRankConfVO communityServiceRankConf(EcologyPoolCommunityServiceRankTypeEnum rankType, Long daoId) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getLastActive(rankType, daoId);
        EcologyPoolWebRankConfVO ecologyPoolWebRankConfVO = new EcologyPoolWebRankConfVO();
        if (Objects.nonNull(ecologyPoolCommunityServiceRankConf)) {
            ecologyPoolWebRankConfVO.setId(ecologyPoolCommunityServiceRankConf.getId());
            if (ecologyPoolCommunityServiceRankConf.getEndTime().before(DateTime.now())) {
                ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.NOTHING);
            } else {
                ecologyPoolWebRankConfVO.setStartTime(ecologyPoolCommunityServiceRankConf.getStartTime());
                ecologyPoolWebRankConfVO.setEndTime(ecologyPoolCommunityServiceRankConf.getEndTime());
                ecologyPoolWebRankConfVO.setActivityRule(ecologyPoolCommunityServiceRankConf.getActivityRule());
                ecologyPoolWebRankConfVO.setTopImage(ecologyPoolCommunityServiceRankConf.getTopImage());
                if (ecologyPoolCommunityServiceRankConf.getStartTime().before(DateTime.now())) {
                    ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.STARTED);
                } else {
                    ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.NOT_START);
                }
                ecologyPoolWebRankConfVO.setRankName(ecologyPoolCommunityServiceRankConf.getRankName());
                //region 奖励
                List<EcologyPoolPrize> ecologyPoolPrizeList = ecologyPoolPrizeDao.listPrizeById(ecologyPoolCommunityServiceRankConf.getId(), EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, null);
                if (CollectionUtil.isNotEmpty(ecologyPoolPrizeList)) {
                    List<EcologyPoolWebRankConfPrizeVO> prizeList = new ArrayList<>();
                    ecologyPoolPrizeList.forEach(prize -> {
                        EcologyPoolWebRankConfPrizeVO ecologyPoolWebRankConfPrizeVO = new EcologyPoolWebRankConfPrizeVO();
                        ecologyPoolWebRankConfPrizeVO.setPrizeType(prize.getLinkType());
                        ecologyPoolWebRankConfPrizeVO.setPrizeTypeName(prize.getLinkType().getDesc());
                        if (Objects.equals(prize.getLinkType(), EcologyPoolLinkTypeEnum.POINTS)) {
                            EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, daoId);
                            if (Objects.nonNull(ecologyPool) && StrUtil.isNotBlank(ecologyPool.getPoolName())) {
                                ecologyPoolWebRankConfPrizeVO.setPrizeTypeName(ecologyPool.getPoolName());
                            }
                        }
                        ecologyPoolWebRankConfPrizeVO.setPrizeCount(prize.getLinkCount());
                        prizeList.add(ecologyPoolWebRankConfPrizeVO);
                    });
                    ecologyPoolWebRankConfVO.setPrizeList(prizeList);
                }
                //endregion
                //region 关联列表
                List<EcologyPoolRelationConditionBind> ecologyPoolRelationConditionBindList = ecologyPoolRelationConditionBindDao.getListByBind(ecologyPoolCommunityServiceRankConf.getId(), EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, null);
                if (CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList)) {
                    List<Long> collectionIdList = ecologyPoolRelationConditionBindList.stream().filter(bind -> Objects.equals(bind.getRelationType(), EcologyPoolRelationTypeEnum.COLLECTION)).map(EcologyPoolRelationConditionBind::getRelationId).distinct().collect(Collectors.toList());
                    List<DigitalCollection> collectionList = CollectionUtil.isNotEmpty(collectionIdList) ? digitalCollectionDao.getByIds(collectionIdList) : new ArrayList<>();
                    if (CollectionUtil.isNotEmpty(collectionList)) {
                        List<EcologyPoolWebRankConfRelationVO> ecologyPoolWebRankConfRelationVOList = new ArrayList<>();
                        collectionList.forEach(collection -> {
                            EcologyPoolWebRankConfRelationVO ecologyPoolWebRankConfRelationVO = new EcologyPoolWebRankConfRelationVO();
                            ecologyPoolWebRankConfRelationVO.setRelationType(EcologyPoolRelationTypeEnum.COLLECTION);
                            ecologyPoolWebRankConfRelationVO.setRelationTypeName(EcologyPoolRelationTypeEnum.COLLECTION.getDesc());
                            ecologyPoolWebRankConfRelationVO.setRelationName(collection.getFirstTitle());
                            ecologyPoolWebRankConfRelationVOList.add(ecologyPoolWebRankConfRelationVO);
                        });
                        ecologyPoolWebRankConfVO.setRelationList(ecologyPoolWebRankConfRelationVOList);
                    }
                }
                //endregion
            }
        } else {
            ecologyPoolWebRankConfVO.setShowStatus(EcologyPoolDaoRankConfShowStatusEnum.NOTHING);
        }
        return ecologyPoolWebRankConfVO;
    }

    @Override
    public EcologyPoolHistoryDaoRankConfVo historyCommunityServiceRankConfDetail(Long id) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            throw new GlobalRunTimeException("排行榜不存在");
        }
        EcologyPoolHistoryDaoRankConfVo ecologyPoolHistoryDaoRankConfVo = new EcologyPoolHistoryDaoRankConfVo();
        ecologyPoolHistoryDaoRankConfVo.setId(ecologyPoolCommunityServiceRankConf.getId());
        ecologyPoolHistoryDaoRankConfVo.setStartTime(ecologyPoolCommunityServiceRankConf.getStartTime());
        ecologyPoolHistoryDaoRankConfVo.setEndTime(ecologyPoolCommunityServiceRankConf.getEndTime());
        ecologyPoolHistoryDaoRankConfVo.setActivityRule(ecologyPoolCommunityServiceRankConf.getActivityRule());
        ecologyPoolHistoryDaoRankConfVo.setTopImage(ecologyPoolCommunityServiceRankConf.getTopImage());
        ecologyPoolHistoryDaoRankConfVo.setRankName(ecologyPoolCommunityServiceRankConf.getRankName());
        //region 奖励
        List<EcologyPoolPrize> ecologyPoolPrizeList = ecologyPoolPrizeDao.listPrizeById(ecologyPoolCommunityServiceRankConf.getId(), EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, null);
        if (CollectionUtil.isNotEmpty(ecologyPoolPrizeList)) {
            List<EcologyPoolWebRankConfPrizeVO> prizeList = new ArrayList<>();
            ecologyPoolPrizeList.forEach(prize -> {
                EcologyPoolWebRankConfPrizeVO ecologyPoolWebRankConfPrizeVO = new EcologyPoolWebRankConfPrizeVO();
                ecologyPoolWebRankConfPrizeVO.setPrizeType(prize.getLinkType());
                ecologyPoolWebRankConfPrizeVO.setPrizeTypeName(prize.getLinkType().getDesc());
                if (Objects.equals(prize.getLinkType(), EcologyPoolLinkTypeEnum.POINTS) && Objects.nonNull(ecologyPoolCommunityServiceRankConf.getDaoId())) {
                    EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, ecologyPoolCommunityServiceRankConf.getDaoId());
                    if (Objects.nonNull(ecologyPool) && StrUtil.isNotBlank(ecologyPool.getPoolName())) {
                        ecologyPoolWebRankConfPrizeVO.setPrizeTypeName(ecologyPool.getPoolName());
                    }
                }
                ecologyPoolWebRankConfPrizeVO.setPrizeCount(prize.getLinkCount());
                prizeList.add(ecologyPoolWebRankConfPrizeVO);
            });
            ecologyPoolHistoryDaoRankConfVo.setPrizeList(prizeList);
        }
        //endregion
        //region 关联列表
        List<EcologyPoolRelationConditionBind> ecologyPoolRelationConditionBindList = ecologyPoolRelationConditionBindDao.getListByBind(ecologyPoolCommunityServiceRankConf.getId(), EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, null);
        if (CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList)) {
            List<Long> collectionIdList = ecologyPoolRelationConditionBindList.stream().filter(bind -> Objects.equals(bind.getRelationType(), EcologyPoolRelationTypeEnum.COLLECTION)).map(EcologyPoolRelationConditionBind::getRelationId).distinct().collect(Collectors.toList());
            List<DigitalCollection> collectionList = CollectionUtil.isNotEmpty(collectionIdList) ? digitalCollectionDao.getByIds(collectionIdList) : new ArrayList<>();
            if (CollectionUtil.isNotEmpty(collectionList)) {
                List<EcologyPoolWebRankConfRelationVO> ecologyPoolWebRankConfRelationVOList = new ArrayList<>();
                collectionList.forEach(collection -> {
                    EcologyPoolWebRankConfRelationVO ecologyPoolWebRankConfRelationVO = new EcologyPoolWebRankConfRelationVO();
                    ecologyPoolWebRankConfRelationVO.setRelationType(EcologyPoolRelationTypeEnum.COLLECTION);
                    ecologyPoolWebRankConfRelationVO.setRelationTypeName(EcologyPoolRelationTypeEnum.COLLECTION.getDesc());
                    ecologyPoolWebRankConfRelationVO.setRelationName(collection.getFirstTitle());
                    ecologyPoolWebRankConfRelationVOList.add(ecologyPoolWebRankConfRelationVO);
                });
                ecologyPoolHistoryDaoRankConfVo.setRelationList(ecologyPoolWebRankConfRelationVOList);
            }
        }
        //endregion
        return ecologyPoolHistoryDaoRankConfVo;
    }

    @Override
    public IPage<EcologyPoolWebCommunityServiceRankVO> communityServiceRankPage(Integer pageNo, Integer pageSize, EcologyPoolCommunityServiceRankTypeEnum rankType, Long daoId) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getLastActive(rankType, daoId);
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            return new Page<>(pageNo, pageSize);
        }
        if (!ecologyPoolCommunityServiceRankConf.getStartTime().before(DateTime.now())) {
            return new Page<>(pageNo, pageSize);
        }
        EcologyPoolCommunityServiceRank ecologyPoolCommunityServiceRank = ecologyPoolCommunityServiceRankDao.getMaxRankDate(ecologyPoolCommunityServiceRankConf.getId());
        if (Objects.isNull(ecologyPoolCommunityServiceRank)) {
            return new Page<>(pageNo, pageSize);
        }
        return ecologyPoolCommunityServiceRankDao.showPage(new Page<>(pageNo, pageSize), ecologyPoolCommunityServiceRank.getEcologyPoolCommunityServiceRankConfId(), ecologyPoolCommunityServiceRank.getRankDate()).convert(record -> {
            EcologyPoolWebCommunityServiceRankVO resultRecord = new EcologyPoolWebCommunityServiceRankVO();
            resultRecord.setHasSort(record.getHasSort());
            resultRecord.setSort(record.getSort());
            int sortChange = Objects.nonNull(record.getSortChange()) ? record.getSortChange() : 0;
            EcologyPoolDaoRankSortChangeSignEnum sortChangeSign = sortChange > 0 ? EcologyPoolDaoRankSortChangeSignEnum.DECLINE : (sortChange < 0 ? EcologyPoolDaoRankSortChangeSignEnum.RISE : EcologyPoolDaoRankSortChangeSignEnum.UNCHANGED);
            resultRecord.setSortChange(sortChange);
            resultRecord.setSortChangeSign(sortChangeSign);
            resultRecord.setRankName(record.getRankName());
            resultRecord.setNewUserCount(record.getNewUserCount());
            resultRecord.setNewEcologySmelting(record.getNewEcologySmelting().setScale(2, RoundingMode.HALF_UP).toPlainString());
            return resultRecord;
        });
    }

    @Override
    public IPage<EcologyPoolWebHistoryCommunityServiceRankConfVO> historyCommunityServiceRankConfPage(Integer pageNo, Integer pageSize, EcologyPoolCommunityServiceRankTypeEnum rankType, Long daoId) {
        return ecologyPoolCommunityServiceRankConfDao.historyRankPage(pageNo, pageSize, rankType, daoId).convert(page -> {
            EcologyPoolWebHistoryCommunityServiceRankConfVO ecologyPoolWebHistoryCommunityServiceRankConfVO = new EcologyPoolWebHistoryCommunityServiceRankConfVO();
            ecologyPoolWebHistoryCommunityServiceRankConfVO.setId(page.getId());
            ecologyPoolWebHistoryCommunityServiceRankConfVO.setRankName(page.getRankName());
            ecologyPoolWebHistoryCommunityServiceRankConfVO.setStartTime(page.getStartTime());
            ecologyPoolWebHistoryCommunityServiceRankConfVO.setEndTime(page.getEndTime());
            return ecologyPoolWebHistoryCommunityServiceRankConfVO;
        });
    }

    @Override
    public IPage<EcologyPoolWebCommunityServiceRankVO> historyCommunityServiceRankPage(Integer pageNo, Integer pageSize, Long id) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            return new Page<>(pageNo, pageSize);
        }
        EcologyPoolCommunityServiceRank ecologyPoolCommunityServiceRank = ecologyPoolCommunityServiceRankDao.getMaxRankDate(ecologyPoolCommunityServiceRankConf.getId());
        if (Objects.isNull(ecologyPoolCommunityServiceRank)) {
            return new Page<>(pageNo, pageSize);
        }
        return ecologyPoolCommunityServiceRankDao.showPage(new Page<>(pageNo, pageSize), ecologyPoolCommunityServiceRank.getEcologyPoolCommunityServiceRankConfId(), ecologyPoolCommunityServiceRank.getRankDate()).convert(page -> {
            EcologyPoolWebCommunityServiceRankVO ecologyPoolWebHistoryDaoRankVO = new EcologyPoolWebCommunityServiceRankVO();
            ecologyPoolWebHistoryDaoRankVO.setHasSort(page.getHasSort());
            ecologyPoolWebHistoryDaoRankVO.setSort(page.getSort());
            int sortChange = Objects.nonNull(page.getSortChange()) ? page.getSortChange() : 0;
            EcologyPoolDaoRankSortChangeSignEnum sortChangeSign = sortChange > 0 ? EcologyPoolDaoRankSortChangeSignEnum.DECLINE : (sortChange < 0 ? EcologyPoolDaoRankSortChangeSignEnum.RISE : EcologyPoolDaoRankSortChangeSignEnum.UNCHANGED);
            ecologyPoolWebHistoryDaoRankVO.setSortChange(sortChange);
            ecologyPoolWebHistoryDaoRankVO.setSortChangeSign(sortChangeSign);
            ecologyPoolWebHistoryDaoRankVO.setRankName(page.getRankName());
            ecologyPoolWebHistoryDaoRankVO.setNewUserCount(page.getNewUserCount());
            ecologyPoolWebHistoryDaoRankVO.setNewEcologySmelting(page.getNewEcologySmelting().setScale(2, RoundingMode.HALF_UP).toPlainString());
            return ecologyPoolWebHistoryDaoRankVO;
        });
    }

    @Override
    public EcologyPoolWebMyCommunityServiceRankVO myCommunityServiceRank(EcologyPoolCommunityServiceRankTypeEnum rankType, UserInfo user, Long daoId) {
        EcologyPoolWebMyCommunityServiceRankVO ecologyPoolWebMyCommunityServiceRankVO = new EcologyPoolWebMyCommunityServiceRankVO();
        ecologyPoolWebMyCommunityServiceRankVO.setShowStatus(EcologyPoolWebMyCommunityStatusEnum.NO_ORG);
        Long userId = null;
        //region 先查询账号本身是否服务中心或社区网点，如果是，则优先取本身账号信息
        if (Objects.equals(rankType.getCode(), EcologyPoolCommunityServiceRankTypeEnum.SERVICE_CENTER.getCode())) {
            UserCityServerCentre userCityServerCentre = userCityServerCentreDao.getByUserId(user.getId());
            if (Objects.nonNull(userCityServerCentre)) {
                ecologyPoolWebMyCommunityServiceRankVO.setRankName(StrUtil.format("{}{}{}", userCityServerCentre.getProvince(), userCityServerCentre.getCity(), userCityServerCentre.getDistrict()));
                userId = user.getId();
            }
        } else {
            UserWorkRoom userWorkRoom = userWorkRoomDao.getByUserId(userId);
            if (Objects.nonNull(userWorkRoom)) {
                ecologyPoolWebMyCommunityServiceRankVO.setRankName(userWorkRoom.getWorkName());
                userId = user.getId();
            }
        }
        //endregion
        //region 如果账号本身不是社区网点或服务中心，则取上级信息
        if (Objects.isNull(userId)) {
            userId = Objects.equals(rankType.getCode(), EcologyPoolCommunityServiceRankTypeEnum.SERVICE_CENTER.getCode()) ? userRelevanceDao.getNearDirectCityServer(user.getId()) : userRelevanceDao.getNearDirectWorkRoom(user.getId());
            if (Objects.isNull(userId)) {
                return ecologyPoolWebMyCommunityServiceRankVO;
            }
            if (Objects.equals(rankType.getCode(), EcologyPoolCommunityServiceRankTypeEnum.SERVICE_CENTER.getCode())) {
                UserCityServerCentre userCityServerCentre = userCityServerCentreDao.getByUserId(userId);
                if (Objects.isNull(userCityServerCentre)) {
                    return ecologyPoolWebMyCommunityServiceRankVO;
                }
                ecologyPoolWebMyCommunityServiceRankVO.setRankName(StrUtil.format("{}{}{}", userCityServerCentre.getProvince(), userCityServerCentre.getCity(), userCityServerCentre.getDistrict()));
            } else {
                UserWorkRoom userWorkRoom = userWorkRoomDao.getByUserId(userId);
                if (Objects.isNull(userWorkRoom)) {
                    return ecologyPoolWebMyCommunityServiceRankVO;
                }
                ecologyPoolWebMyCommunityServiceRankVO.setRankName(userWorkRoom.getWorkName());
            }
        }
        //endregion
        ecologyPoolWebMyCommunityServiceRankVO.setShowStatus(EcologyPoolWebMyCommunityStatusEnum.NO_JOIN);
        ecologyPoolWebMyCommunityServiceRankVO.setNewUserCount(0);
        ecologyPoolWebMyCommunityServiceRankVO.setNewEcologySmelting("0.00");
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getLastActive(rankType, daoId);
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            return ecologyPoolWebMyCommunityServiceRankVO;
        }
        if (!ecologyPoolCommunityServiceRankConf.getStartTime().before(DateTime.now())) {
            return ecologyPoolWebMyCommunityServiceRankVO;
        }
        EcologyPoolCommunityServiceRank ecologyPoolCommunityServiceRank = ecologyPoolCommunityServiceRankDao.getMaxRankDate(ecologyPoolCommunityServiceRankConf.getId());
        if (Objects.isNull(ecologyPoolCommunityServiceRank)) {
            return ecologyPoolWebMyCommunityServiceRankVO;
        }
        ecologyPoolCommunityServiceRank = ecologyPoolCommunityServiceRankDao.getOneByDateAndUser(ecologyPoolCommunityServiceRankConf.getId(), ecologyPoolCommunityServiceRank.getRankDate(), ecologyPoolCommunityServiceRankConf.getDaoId(), userId);
        if (Objects.nonNull(ecologyPoolCommunityServiceRank)) {
            ecologyPoolWebMyCommunityServiceRankVO.setHasSort(ecologyPoolCommunityServiceRank.getHasSort());
            ecologyPoolWebMyCommunityServiceRankVO.setSort(ecologyPoolCommunityServiceRank.getSort());
            ecologyPoolWebMyCommunityServiceRankVO.setShowStatus(ecologyPoolCommunityServiceRank.getShowStatus() ? EcologyPoolWebMyCommunityStatusEnum.JOINING : EcologyPoolWebMyCommunityStatusEnum.NO_JOIN);
            int sortChange = Objects.nonNull(ecologyPoolCommunityServiceRank.getSortChange()) ? ecologyPoolCommunityServiceRank.getSortChange() : 0;
            EcologyPoolDaoRankSortChangeSignEnum sortChangeSign = sortChange > 0 ? EcologyPoolDaoRankSortChangeSignEnum.DECLINE : (sortChange < 0 ? EcologyPoolDaoRankSortChangeSignEnum.RISE : EcologyPoolDaoRankSortChangeSignEnum.UNCHANGED);
            ecologyPoolWebMyCommunityServiceRankVO.setSortChange(sortChange);
            ecologyPoolWebMyCommunityServiceRankVO.setSortChangeSign(sortChangeSign);
            ecologyPoolWebMyCommunityServiceRankVO.setRankName(ecologyPoolCommunityServiceRank.getRankName());
            ecologyPoolWebMyCommunityServiceRankVO.setNewUserCount(ecologyPoolCommunityServiceRank.getNewUserCount());
            ecologyPoolWebMyCommunityServiceRankVO.setNewEcologySmelting(ecologyPoolCommunityServiceRank.getNewEcologySmelting().setScale(2, RoundingMode.HALF_UP).toPlainString());
        }
        return ecologyPoolWebMyCommunityServiceRankVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void increasePoints(EcologyPoolIncreasePointsDTO ecologyPoolIncreasePointsDTO) {
        //校验参数
        validateIncreasePoints(ecologyPoolIncreasePointsDTO);
        //执行减积分
        doIncreasePoints(ecologyPoolIncreasePointsDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reducePoints(EcologyPoolReducePointsDTO ecologyPoolReducePointsDTO) {
        //校验参数
        validateReducePoints(ecologyPoolReducePointsDTO);
        //执行加积分
        doReducePoints(ecologyPoolReducePointsDTO);
    }

    @Override
    public Boolean updatePoolName(Long id, Long daoId, String poolName) {
        Assert.notBlank(poolName, () -> new GlobalRunTimeException("生态池名称不能为空"));
        poolName = poolName.trim();
        Assert.notBlank(poolName, () -> new GlobalRunTimeException("生态池名称不能为空"));
        Assert.isTrue(poolName.length() <= 8, () -> new GlobalRunTimeException("生态池名称限制为8个字符"));
        EcologyPool ecologyPool = ecologyPoolDao.getById(id);
        Assert.notNull(ecologyPool, () -> new GlobalRunTimeException("生态池不存在"));
        Assert.isTrue(Objects.equals(ecologyPool.getDaoId(), daoId), () -> new GlobalRunTimeException("生态池与品牌DAO不匹配"));
        ecologyPoolDao.updatePoolName(id, poolName, ecologyPool.getVersion());
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createDaoCommunityServiceRankConf(EcologyPoolCreateDaoCommunityServiceRankConfRpcRequest request) {
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL_CREATE_COMMUNITY_SERVICE_RANK.getKey());
        try {
            if (!lock.tryLock(10, 10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            doCreateDaoCommunityServiceRankConf(request, validateCreateDaoCommunityServiceRankConf(request));
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("创建排行榜异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Override
    public List<EcologyPoolHatchCollectionVo> hatchCollectionList(String collectionName, Long daoId) {
        List<DigitalCollection> ecologyHatchConfList = digitalCollectionDao.hatchCollectionList(collectionName, daoId);
        if (CollectionUtil.isEmpty(ecologyHatchConfList)) {
            return Collections.emptyList();
        }
        return ecologyHatchConfList.stream().map(collection -> {
            EcologyPoolHatchCollectionVo ecologyPoolHatchCollectionVo = new EcologyPoolHatchCollectionVo();
            ecologyPoolHatchCollectionVo.setCollectionId(collection.getId());
            ecologyPoolHatchCollectionVo.setCollectionName(collection.getFirstTitle());
            return ecologyPoolHatchCollectionVo;
        }).collect(Collectors.toList());
    }

    @Override
    public EcologyPoolGetPoolNameByDaoIdVo getPoolNameByDaoId(Long daoId) {
        EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, daoId);
        EcologyPoolGetPoolNameByDaoIdVo ecologyPoolGetPoolNameByDaoIdVo = new EcologyPoolGetPoolNameByDaoIdVo();
        if (Objects.nonNull(ecologyPool) && StrUtil.isNotBlank(ecologyPool.getPoolName())) {
            ecologyPoolGetPoolNameByDaoIdVo.setPoolName(ecologyPool.getPoolName());
        } else {
            ecologyPoolGetPoolNameByDaoIdVo.setPoolName(EcologyPoolLinkTypeEnum.POINTS.getDesc());
        }
        return ecologyPoolGetPoolNameByDaoIdVo;
    }

    @Override
    public EcologyPoolDaoCommunityServiceRankConfDetailVo daoCommunityServiceRankConfDetail(Long id) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            throw new GlobalRunTimeException("榜单不存在或已被删除");
        }
        EcologyPoolDaoCommunityServiceRankConfDetailVo ecologyPoolCommunityServiceRankConfDetailVO = new EcologyPoolDaoCommunityServiceRankConfDetailVo();
        ecologyPoolCommunityServiceRankConfDetailVO.setId(ecologyPoolCommunityServiceRankConf.getId());
        ecologyPoolCommunityServiceRankConfDetailVO.setDaoId(ecologyPoolCommunityServiceRankConf.getDaoId());
        ecologyPoolCommunityServiceRankConfDetailVO.setRankName(ecologyPoolCommunityServiceRankConf.getRankName());
        ecologyPoolCommunityServiceRankConfDetailVO.setRankType(ecologyPoolCommunityServiceRankConf.getRankType());
        ecologyPoolCommunityServiceRankConfDetailVO.setNewUserCountThreshold(ecologyPoolCommunityServiceRankConf.getNewUserCountThreshold());
        ecologyPoolCommunityServiceRankConfDetailVO.setNewEcologySmeltingThreshold(ecologyPoolCommunityServiceRankConf.getNewEcologySmeltingThreshold());
        ecologyPoolCommunityServiceRankConfDetailVO.setStartTime(ecologyPoolCommunityServiceRankConf.getStartTime());
        ecologyPoolCommunityServiceRankConfDetailVO.setEndTime(ecologyPoolCommunityServiceRankConf.getEndTime());
        ecologyPoolCommunityServiceRankConfDetailVO.setActivityRule(ecologyPoolCommunityServiceRankConf.getActivityRule());
        ecologyPoolCommunityServiceRankConfDetailVO.setTopImage(ecologyPoolCommunityServiceRankConf.getTopImage());
        ecologyPoolCommunityServiceRankConfDetailVO.setStatus(ecologyPoolCommunityServiceRankConf.getStatus());

        //生态池
        EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, ecologyPoolCommunityServiceRankConf.getDaoId());

        //填充榜单收益
        List<EcologyPoolCommunityServiceRankIncomeConf> incomeList = ecologyPoolCommunityServiceRankIncomeConfDao.getListByConfId(id);
        if (CollectionUtil.isNotEmpty(incomeList)) {
            //填充榜单收益条件
            List<EcologyPoolCommunityServiceRankIncomeConditionConf> conditionList = ecologyPoolCommunityServiceRankIncomeConditionConfDao.getListByConfId(id);
            Map<Long, EcologyPoolCommunityServiceRankIncomeConditionConf> conditionMap = CollectionUtil.isNotEmpty(conditionList) ? conditionList.stream().collect(Collectors.toMap(EcologyPoolCommunityServiceRankIncomeConditionConf::getEcologyPoolCommunityServiceRankIncomeConfId, Function.identity())) : new HashMap<>();
            List<EcologyPoolDaoCommunityServiceRankConfDetailIncomeVO> ecologyPoolCommunityServiceRankConfDetailIncomeVOList = new ArrayList<>();
            for (EcologyPoolCommunityServiceRankIncomeConf income : incomeList) {
                //region 填充榜单收益
                EcologyPoolDaoCommunityServiceRankConfDetailIncomeVO ecologyPoolCommunityServiceRankConfDetailIncomeVO = new EcologyPoolDaoCommunityServiceRankConfDetailIncomeVO();
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setSort(income.getSort());
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setIncomeName(income.getIncomeName());
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setStartRank(income.getStartRank());
                ecologyPoolCommunityServiceRankConfDetailIncomeVO.setEndRank(income.getEndRank());
                //region 榜单收益奖励
                List<EcologyPoolPrize> ecologyPoolPrizeList = ecologyPoolPrizeDao.listPrizeById(income.getId(), EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK_INCOME, null);
                if (CollectionUtil.isNotEmpty(ecologyPoolPrizeList)) {
                    List<EcologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO> prizeList = new ArrayList<>();
                    ecologyPoolPrizeList.forEach(prize -> {
                        EcologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO ecologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO = new EcologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO();
                        ecologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO.setPrizeType(prize.getLinkType());
                        ecologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO.setPrizeTypeName(prize.getLinkType().getDesc());
                        ecologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO.setPrizeName(prize.getLinkType().getDesc());
                        //生态池名称
                        if (Objects.nonNull(ecologyPool) && StrUtil.isNotBlank(ecologyPool.getPoolName())) {
                            ecologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO.setPrizeName(ecologyPool.getPoolName());
                        }
                        ecologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO.setPrizeCount(prize.getLinkCount());
                        prizeList.add(ecologyPoolDaoCommunityServiceRankConfDetailIncomePrizeVO);
                    });
                    ecologyPoolCommunityServiceRankConfDetailIncomeVO.setPrizeList(prizeList);
                }
                //endregion

                EcologyPoolCommunityServiceRankIncomeConditionConf condition = conditionMap.get(income.getId());
                if (Objects.nonNull(condition)) {
                    //region 填充榜单收益条件
                    EcologyPoolDaoCommunityServiceRankConfDetailIncomeConditionVO communityServiceRankConfDetailIncomeConditionVO = new EcologyPoolDaoCommunityServiceRankConfDetailIncomeConditionVO();
                    communityServiceRankConfDetailIncomeConditionVO.setNewEcologySmeltingThreshold(condition.getNewEcologySmeltingThreshold());
                    communityServiceRankConfDetailIncomeConditionVO.setNewUserCountThreshold(condition.getNewUserCountThreshold());
                    ecologyPoolCommunityServiceRankConfDetailIncomeVO.setCondition(communityServiceRankConfDetailIncomeConditionVO);
                    //endregion
                }
                ecologyPoolCommunityServiceRankConfDetailIncomeVOList.add(ecologyPoolCommunityServiceRankConfDetailIncomeVO);
                //endregion
            }
            ecologyPoolCommunityServiceRankConfDetailVO.setIncomeList(ecologyPoolCommunityServiceRankConfDetailIncomeVOList);
        }

        //region 填充关联
        List<EcologyPoolRelationConditionBind> ecologyPoolRelationConditionBindList = ecologyPoolRelationConditionBindDao.getListByBind(ecologyPoolCommunityServiceRankConf.getId(), EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, EcologyPoolRelationTypeEnum.COLLECTION);
        if (CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList)) {
            List<Long> relationIdList = ecologyPoolRelationConditionBindList.stream().filter(bind -> Objects.equals(bind.getRelationType(), EcologyPoolRelationTypeEnum.COLLECTION)).map(EcologyPoolRelationConditionBind::getRelationId).collect(Collectors.toList());
            List<DigitalCollection> collectionList = CollectionUtil.isNotEmpty(relationIdList) ? digitalCollectionDao.getByIds(relationIdList) : new ArrayList<>();
            Map<Long, DigitalCollection> collectionMap = CollectionUtil.isNotEmpty(collectionList) ? collectionList.stream().collect(Collectors.toMap(DigitalCollection::getId, Function.identity())) : new HashMap<>();
            List<EcologyPoolDaoCommunityServiceRankConfDetailRelationVO> ecologyPoolDaoCommunityServiceRankConfDetailRelationVOList = new ArrayList<>();
            ecologyPoolRelationConditionBindList.forEach(bind -> {
                EcologyPoolDaoCommunityServiceRankConfDetailRelationVO ecologyPoolDaoCommunityServiceRankConfDetailRelationVO = new EcologyPoolDaoCommunityServiceRankConfDetailRelationVO();
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVO.setRelationType(bind.getRelationType());
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVO.setRelationTypeName(bind.getRelationType().getDesc());
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVO.setRelationId(bind.getRelationId());
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVO.setRelationName(Objects.nonNull(collectionMap.get(bind.getRelationId())) ? collectionMap.get(bind.getRelationId()).getFirstTitle() : "");
                ecologyPoolDaoCommunityServiceRankConfDetailRelationVOList.add(ecologyPoolDaoCommunityServiceRankConfDetailRelationVO);
            });
            ecologyPoolCommunityServiceRankConfDetailVO.setRelationList(ecologyPoolDaoCommunityServiceRankConfDetailRelationVOList);
        }
        //endregion
        ecologyPoolCommunityServiceRankConfDetailVO.setAllRelation(CollectionUtil.isEmpty(ecologyPoolCommunityServiceRankConfDetailVO.getRelationList()));
        return ecologyPoolCommunityServiceRankConfDetailVO;
    }

    @Override
    public Page<EcologyPoolDaoCommunityServiceRankConfVo> daoCommunityServiceRankConfPage(Integer pageNo, Integer pageSize, String rankName, EcologyPoolCommunityServiceRankApprovalStatusEnum approvalStatus, Long daoId) {
        Page<EcologyPoolCommunityServiceRankConf> page = ecologyPoolCommunityServiceRankConfDao.page(new Page<>(pageNo, pageSize), rankName, approvalStatus, daoId, META_DAO_ID);
        Page<EcologyPoolDaoCommunityServiceRankConfVo> resultPage = new Page<>();
        List<EcologyPoolDaoCommunityServiceRankConfVo> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<Long> confIdList = page.getRecords().stream().map(EcologyPoolCommunityServiceRankConf::getId).distinct().collect(Collectors.toList());
            List<EcologyPoolRelationConditionBind> ecologyPoolRelationConditionBindList = ecologyPoolRelationConditionBindDao.getListByBinds(confIdList, EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, EcologyPoolRelationTypeEnum.COLLECTION);
            Map<Long, List<EcologyPoolRelationConditionBind>> ecologyPoolRelationConditionBindMap = CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList) ? ecologyPoolRelationConditionBindList.stream().collect(Collectors.groupingBy(EcologyPoolRelationConditionBind::getBindId)) : new HashMap<>();
            List<Long> collectionIdList = CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList) ? ecologyPoolRelationConditionBindList.stream().map(EcologyPoolRelationConditionBind::getRelationId).distinct().collect(Collectors.toList()) : new ArrayList<>();
            List<DigitalCollection> digitalCollectionList = CollectionUtil.isNotEmpty(collectionIdList) ? digitalCollectionDao.getByIds(collectionIdList) : new ArrayList<>();
            Map<Long, DigitalCollection> digitalCollectionMap = CollectionUtil.isNotEmpty(digitalCollectionList) ? digitalCollectionList.stream().collect(Collectors.toMap(DigitalCollection::getId, Function.identity())) : new HashMap<>();
            page.getRecords().forEach(record -> {
                EcologyPoolDaoCommunityServiceRankConfVo resultRecord = new EcologyPoolDaoCommunityServiceRankConfVo();
                resultRecord.setId(record.getId());
                resultRecord.setRankName(record.getRankName());
                resultRecord.setRankType(record.getRankType());
                resultRecord.setRankTypeName(record.getRankType().getDesc());
                resultRecord.setStartTime(record.getStartTime());
                resultRecord.setEndTime(record.getEndTime());
                resultRecord.setJoinRankCount(record.getJoinRankCount());
                resultRecord.setStatus(record.getStatus());
                resultRecord.setApprovalStatus(record.getApprovalStatus());
                resultRecord.setApprovalStatusName(record.getApprovalStatus().getDesc());
                resultRecord.setApprovalMessage(record.getApprovalMessage());
                String collectionNames = "";
                List<EcologyPoolRelationConditionBind> bindList = ecologyPoolRelationConditionBindMap.get(record.getId());
                if (CollectionUtil.isNotEmpty(bindList)) {
                    collectionNames = bindList.stream().filter(bind -> Objects.nonNull(digitalCollectionMap.get(bind.getRelationId()))).map(bind -> digitalCollectionMap.get(bind.getRelationId()).getFirstTitle())
                            .collect(Collectors.joining(","));
                }
                resultRecord.setCollectionNames(collectionNames);
                resultRecord.setCreateTime(record.getCreateTime());
                resultRecords.add(resultRecord);
            });
        }
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        resultPage.setTotal(page.getTotal());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    public List<EcologyPoolCommunityServiceRankPrizeVo> communityServiceRankPrize(Long id) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        if (Objects.isNull(ecologyPoolCommunityServiceRankConf)) {
            return Collections.emptyList();
        }
        List<EcologyPoolCommunityServiceRankIncomeConf> ecologyPoolCommunityServiceRankIncomeConfList = ecologyPoolCommunityServiceRankIncomeConfDao.getListByConfId(id);
        if (CollectionUtil.isEmpty(ecologyPoolCommunityServiceRankIncomeConfList)) {
            return Collections.emptyList();
        }
        List<Long> incomeIdList = ecologyPoolCommunityServiceRankIncomeConfList.stream().map(EcologyPoolCommunityServiceRankIncomeConf::getId).collect(Collectors.toList());
        List<EcologyPoolPrize> ecologyPoolPrizeList = ecologyPoolPrizeDao.listPrizeById(incomeIdList, EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK_INCOME, null);
        Map<Long, List<EcologyPoolPrize>> ecologyPoolPrizeMap = CollectionUtil.isNotEmpty(ecologyPoolPrizeList) ? ecologyPoolPrizeList.stream().collect(Collectors.groupingBy(EcologyPoolPrize::getBindId)) : new HashMap<>();
        List<EcologyPoolCommunityServiceRankPrizeVo> ecologyPoolCommunityServiceRankPrizeVoList = new ArrayList<>();
        ecologyPoolCommunityServiceRankIncomeConfList.forEach(income -> {
            for (int i = income.getStartRank() + 1; i <= income.getEndRank(); i++) {
                List<EcologyPoolPrize> prizeList = ecologyPoolPrizeMap.get(income.getId());
                if (CollectionUtil.isNotEmpty(prizeList)) {
                    EcologyPoolCommunityServiceRankPrizeVo ecologyPoolCommunityServiceRankPrizeVo = new EcologyPoolCommunityServiceRankPrizeVo();
                    ecologyPoolCommunityServiceRankPrizeVo.setSort("第" + i + "名");
                    List<EcologyPoolCommunityServiceRankPrizeDataVo> dataVoList = new ArrayList<>();
                    prizeList.forEach(prize -> {
                        EcologyPoolCommunityServiceRankPrizeDataVo ecologyPoolCommunityServiceRankPrizeDataVo = new EcologyPoolCommunityServiceRankPrizeDataVo();
                        ecologyPoolCommunityServiceRankPrizeDataVo.setPrizeType(prize.getLinkType());
                        ecologyPoolCommunityServiceRankPrizeDataVo.setPrizeTypeName(prize.getLinkType().getDesc());
                        ecologyPoolCommunityServiceRankPrizeDataVo.setPrizeCount(prize.getLinkCount().toPlainString());
                        dataVoList.add(ecologyPoolCommunityServiceRankPrizeDataVo);
                    });
                    ecologyPoolCommunityServiceRankPrizeVo.setPrizeList(dataVoList);
                    ecologyPoolCommunityServiceRankPrizeVoList.add(ecologyPoolCommunityServiceRankPrizeVo);
                }
            }
        });
        return ecologyPoolCommunityServiceRankPrizeVoList;
    }

    @Override
    public Page<EcologyPoolDaoCommunityServiceRankConfVo> daoCommunityServiceRankConfPage(Integer pageNo, Integer pageSize, String rankName, Long daoId, EcologyPoolCommunityServiceRankApprovalStatusEnum approvalStatus) {
        Page<EcologyPoolCommunityServiceRankConf> page = ecologyPoolCommunityServiceRankConfDao.page(new Page<>(pageNo, pageSize), rankName, approvalStatus, daoId, META_DAO_ID);
        Page<EcologyPoolDaoCommunityServiceRankConfVo> resultPage = new Page<>();
        List<EcologyPoolDaoCommunityServiceRankConfVo> resultRecords = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            List<Long> daoIdList = page.getRecords().stream().map(EcologyPoolCommunityServiceRankConf::getDaoId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            List<UserCreatorInfo> userCreatorInfoList = CollectionUtil.isNotEmpty(daoIdList) ? userCreatorInfoDao.getDaoByIds(daoIdList) : new ArrayList<>();
            Map<Long, UserCreatorInfo> userCreatorInfoMap = CollectionUtil.isNotEmpty(userCreatorInfoList) ? userCreatorInfoList.stream().collect(Collectors.toMap(UserCreatorInfo::getId, Function.identity())) : new HashMap<>();
            List<Long> confIdList = page.getRecords().stream().map(EcologyPoolCommunityServiceRankConf::getId).distinct().collect(Collectors.toList());
            List<EcologyPoolRelationConditionBind> ecologyPoolRelationConditionBindList = ecologyPoolRelationConditionBindDao.getListByBinds(confIdList, EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, EcologyPoolRelationTypeEnum.COLLECTION);
            Map<Long, List<EcologyPoolRelationConditionBind>> ecologyPoolRelationConditionBindMap = CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList) ? ecologyPoolRelationConditionBindList.stream().collect(Collectors.groupingBy(EcologyPoolRelationConditionBind::getBindId)) : new HashMap<>();
            List<Long> collectionIdList = CollectionUtil.isNotEmpty(ecologyPoolRelationConditionBindList) ? ecologyPoolRelationConditionBindList.stream().map(EcologyPoolRelationConditionBind::getRelationId).distinct().collect(Collectors.toList()) : new ArrayList<>();
            List<DigitalCollection> digitalCollectionList = CollectionUtil.isNotEmpty(collectionIdList) ? digitalCollectionDao.getByIds(collectionIdList) : new ArrayList<>();
            Map<Long, DigitalCollection> digitalCollectionMap = CollectionUtil.isNotEmpty(digitalCollectionList) ? digitalCollectionList.stream().collect(Collectors.toMap(DigitalCollection::getId, Function.identity())) : new HashMap<>();
            page.getRecords().forEach(record -> {
                EcologyPoolDaoCommunityServiceRankConfVo resultRecord = new EcologyPoolDaoCommunityServiceRankConfVo();
                resultRecord.setId(record.getId());
                resultRecord.setRankName(record.getRankName());
                resultRecord.setRankType(record.getRankType());
                resultRecord.setRankTypeName(record.getRankType().getDesc());
                resultRecord.setStartTime(record.getStartTime());
                resultRecord.setEndTime(record.getEndTime());
                resultRecord.setJoinRankCount(record.getJoinRankCount());
                resultRecord.setStatus(record.getStatus());
                resultRecord.setApprovalStatus(record.getApprovalStatus());
                resultRecord.setApprovalStatusName(record.getApprovalStatus().getDesc());
                resultRecord.setApprovalMessage(record.getApprovalMessage());
                String collectionNames = "";
                List<EcologyPoolRelationConditionBind> bindList = ecologyPoolRelationConditionBindMap.get(record.getId());
                if (CollectionUtil.isNotEmpty(bindList)) {
                    collectionNames = bindList.stream().filter(bind -> Objects.nonNull(digitalCollectionMap.get(bind.getRelationId()))).map(bind -> digitalCollectionMap.get(bind.getRelationId()).getFirstTitle())
                            .collect(Collectors.joining(","));
                }
                resultRecord.setCollectionNames(collectionNames);
                resultRecord.setCreateTime(record.getCreateTime());
                String daoName = "";
                if (Objects.nonNull(record.getDaoId())) {
                    UserCreatorInfo userCreatorInfo = userCreatorInfoMap.get(record.getDaoId());
                    if (Objects.nonNull(userCreatorInfo)) {
                        daoName = userCreatorInfo.getDaoName();
                    }
                }
                resultRecord.setDaoName(daoName);
                resultRecords.add(resultRecord);
            });
        }
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        resultPage.setTotal(page.getTotal());
        resultPage.setRecords(resultRecords);
        return resultPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean daoCommunityServiceRankConfApproval(Long id, EcologyPoolCommunityServiceRankApprovalStatusEnum approvalStatus, String approvalMessage) {
        if (!Objects.equals(approvalStatus, EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_SUCCESS)
                && !Objects.equals(approvalStatus, EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_FAIL)) {
            throw new GlobalRunTimeException("审核状态只能是审核成功或审核失败");
        }
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getById(id);
        Assert.notNull(ecologyPoolCommunityServiceRankConf, () -> new GlobalRunTimeException("排行榜不存在"));
        if (Objects.equals(ecologyPoolCommunityServiceRankConf.getApprovalStatus(), EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_SUCCESS)) {
            throw new GlobalRunTimeException("排行榜已审核通过");
        }
        if (Objects.equals(ecologyPoolCommunityServiceRankConf.getApprovalStatus(), EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_FAIL)) {
            throw new GlobalRunTimeException("排行榜已审核拒绝");
        }
        if (Objects.equals(approvalStatus, EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_SUCCESS)) {
            ecologyPoolCommunityServiceRankConf.setStatus(Boolean.TRUE);
        }
        if (Objects.equals(approvalStatus, EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_FAIL)) {
            if (StrUtil.isBlank(approvalMessage)) {
                throw new GlobalRunTimeException("审核失败原因不能为空");
            }
            ecologyPoolCommunityServiceRankConf.setApprovalMessage(approvalMessage);
            ecologyPoolCommunityServiceRankConf.setSettled(Boolean.TRUE);
        }
        ecologyPoolCommunityServiceRankConf.setApprovalStatus(approvalStatus);
        ecologyPoolCommunityServiceRankConf.updateById();
        if (Objects.equals(approvalStatus, EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_FAIL)) {
            EcologyPoolPrize ecologyPoolPrize = ecologyPoolPrizeDao.getPrizeById(id, EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK, EcologyPoolLinkTypeEnum.POINTS);
            if (Objects.nonNull(ecologyPoolPrize) && ecologyPoolPrize.getLinkCount().compareTo(BigDecimal.ZERO) > 0) {
                EcologyPoolIncreasePointsDTO ecologyPoolIncreasePointsDTO = EcologyPoolIncreasePointsDTO.builder()
                        .linkCount(ecologyPoolPrize.getLinkCount())
                        .linkType(ecologyPoolPrize.getLinkType())
                        .daoId(ecologyPoolCommunityServiceRankConf.getDaoId())
                        .poolType(EcologyPoolTypeEnum.BRAND)
                        .operationType(EcologyPoolOperationTypeEnum.BACK_FLOW)
                        .sourcePoolType(Objects.equals(ecologyPoolCommunityServiceRankConf.getRankType(), EcologyPoolCommunityServiceRankTypeEnum.COMMUNITY) ? EcologyPoolTypeEnum.COMMUNITY_NETWORK_RANK : EcologyPoolTypeEnum.SERVICE_CENTER_RANK)
                        .sourceDaoId(ecologyPoolCommunityServiceRankConf.getDaoId())
                        .sourceRelationId(id)
                        .transactionUuid(IdUtil.simpleUUID())
                        .activeOperatorName("排行榜")
                        .passiveOperatorName("品牌生态池")
                        .build();
                this.increasePoints(ecologyPoolIncreasePointsDTO);
            }
        }
        return Boolean.TRUE;
    }

    @Override
    public void convertPoints(BigDecimal linkCount, Long daoId, Long userId) {
        //扣减账户生态积分
        String transactionUuid = IdUtil.simpleUUID();
        EcologyPoolReducePointsDTO ecologyPoolReducePointsDTO = EcologyPoolReducePointsDTO.builder()
                .linkCount(linkCount)
                .linkType(EcologyPoolLinkTypeEnum.POINTS)
                .poolType(EcologyPoolTypeEnum.ACCOUNT)
                .daoId(daoId)
                .userId(userId)
                .operationType(EcologyPoolOperationTypeEnum.CONVERT)
                .sourcePoolType(EcologyPoolTypeEnum.BRAND)
                .sourceDaoId(daoId)
                .transactionUuid(transactionUuid)
                .remark("兑换")
                .activeOperatorName("账户生态池")
                .passiveOperatorName("品牌生态池")
                .build();
        this.reducePoints(ecologyPoolReducePointsDTO);
    }

    /**
     * 校验参数
     *
     * @param ecologyPoolReducePointsDTO
     */
    private void validateReducePoints(EcologyPoolReducePointsDTO ecologyPoolReducePointsDTO) {
        if (Objects.isNull(ecologyPoolReducePointsDTO)) {
            throw new GlobalRunTimeException("分配积分参数不能为空");
        }
        if (Objects.isNull(ecologyPoolReducePointsDTO.getLinkCount())) {
            throw new GlobalRunTimeException("物质数量不能为空");
        }
        if (ecologyPoolReducePointsDTO.getLinkCount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new GlobalRunTimeException("物质数量必须大于0");
        }
        if (Objects.isNull(ecologyPoolReducePointsDTO.getLinkType())) {
            throw new GlobalRunTimeException("物质类型不能为空");
        }
        if (Objects.isNull(ecologyPoolReducePointsDTO.getDaoId())) {
            throw new GlobalRunTimeException("主动操作方品牌ID不能为空");
        }
        if (Objects.isNull(ecologyPoolReducePointsDTO.getPoolType())) {
            throw new GlobalRunTimeException("主动操作方类型不能为空");
        }
        if (Objects.isNull(ecologyPoolReducePointsDTO.getOperationType())) {
            throw new GlobalRunTimeException("操作方式不能为空");
        }
        if (Objects.isNull(ecologyPoolReducePointsDTO.getSourcePoolType())) {
            throw new GlobalRunTimeException("被动操作方类型不能为空");
        }
        if (Objects.isNull(ecologyPoolReducePointsDTO.getSourceDaoId())) {
            throw new GlobalRunTimeException("被动操作方品牌ID不能为空");
        }
    }

    /**
     * 校验参数
     *
     * @param ecologyPoolIncreasePointsDTO
     */
    private void validateIncreasePoints(EcologyPoolIncreasePointsDTO ecologyPoolIncreasePointsDTO) {
        if (Objects.isNull(ecologyPoolIncreasePointsDTO)) {
            throw new GlobalRunTimeException("分配积分参数不能为空");
        }
        if (Objects.isNull(ecologyPoolIncreasePointsDTO.getLinkCount())) {
            throw new GlobalRunTimeException("物质数量不能为空");
        }
        if (ecologyPoolIncreasePointsDTO.getLinkCount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new GlobalRunTimeException("物质数量必须大于0");
        }
        if (Objects.isNull(ecologyPoolIncreasePointsDTO.getLinkType())) {
            throw new GlobalRunTimeException("物质类型不能为空");
        }
        if (Objects.isNull(ecologyPoolIncreasePointsDTO.getDaoId())) {
            throw new GlobalRunTimeException("主动操作方品牌ID不能为空");
        }
        if (Objects.isNull(ecologyPoolIncreasePointsDTO.getPoolType())) {
            throw new GlobalRunTimeException("主动操作方类型不能为空");
        }
        if (Objects.isNull(ecologyPoolIncreasePointsDTO.getOperationType())) {
            throw new GlobalRunTimeException("操作方式不能为空");
        }
        if (Objects.isNull(ecologyPoolIncreasePointsDTO.getSourcePoolType())) {
            throw new GlobalRunTimeException("被动操作方类型不能为空");
        }
        if (Objects.isNull(ecologyPoolIncreasePointsDTO.getSourceDaoId())) {
            throw new GlobalRunTimeException("被动操作方品牌ID不能为空");
        }
    }

    /**
     * 执行加积分
     *
     * @param ecologyPoolReducePointsDTO
     */
    private void doReducePoints(EcologyPoolReducePointsDTO ecologyPoolReducePointsDTO) {
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL.getKey() + "_" + ecologyPoolReducePointsDTO.buildPkCode());
        try {
            if (!lock.tryLock(10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            EcologyPool ecologyPool = ecologyPoolDao.getOneByTypeAndDaoIdUserId(ecologyPoolReducePointsDTO.getPoolType(), ecologyPoolReducePointsDTO.getLinkType(), ecologyPoolReducePointsDTO.getDaoId(), ecologyPoolReducePointsDTO.getUserId());
            if (Objects.isNull(ecologyPool)) {
                throw new GlobalRunTimeException("生态池不存在");
            }
            if (ecologyPool.getLinkCount().compareTo(ecologyPoolReducePointsDTO.getLinkCount()) < 0) {
                throw new GlobalRunTimeException("生态池积分不足");
            }

            ecologyPoolDao.reducePoints(ecologyPool.getId(), ecologyPoolReducePointsDTO.getLinkCount(), ecologyPool.getVersion());

            EcologyPoolRecord ecologyPoolRecord = new EcologyPoolRecord();
            ecologyPoolRecord.setLinkCount(ecologyPoolReducePointsDTO.getLinkCount());
            ecologyPoolRecord.setLinkType(ecologyPoolReducePointsDTO.getLinkType());
            ecologyPoolRecord.setBeforeLinkCount(ecologyPool.getLinkCount());
            ecologyPoolRecord.setAfterLinkCount(ecologyPool.getLinkCount().subtract(ecologyPoolReducePointsDTO.getLinkCount()));
            ecologyPoolRecord.setIsAdd(false);
            ecologyPoolRecord.setDaoId(ecologyPoolReducePointsDTO.getDaoId());
            ecologyPoolRecord.setUserId(ecologyPoolReducePointsDTO.getUserId());
            ecologyPoolRecord.setRelationId(ecologyPoolReducePointsDTO.getRelationId());
            ecologyPoolRecord.setPoolType(ecologyPoolReducePointsDTO.getPoolType());
            ecologyPoolRecord.setOperationType(ecologyPoolReducePointsDTO.getOperationType());
            ecologyPoolRecord.setFlowType(EcologyPoolFlowTypeEnum.OUT_FLOW);
            ecologyPoolRecord.setSourcePoolType(ecologyPoolReducePointsDTO.getSourcePoolType());
            ecologyPoolRecord.setSourceDaoId(ecologyPoolReducePointsDTO.getSourceDaoId());
            ecologyPoolRecord.setSourceUserId(ecologyPoolReducePointsDTO.getSourceUserId());
            ecologyPoolRecord.setSourceRelationId(ecologyPoolReducePointsDTO.getSourceRelationId());
            ecologyPoolRecord.setTransactionUuid(ecologyPoolReducePointsDTO.getTransactionUuid());
            ecologyPoolRecord.setRemark(ecologyPoolReducePointsDTO.getRemark());
            ecologyPoolRecord.setActiveOperatorName(ecologyPoolReducePointsDTO.getActiveOperatorName());
            ecologyPoolRecord.setPassiveOperatorName(ecologyPoolReducePointsDTO.getPassiveOperatorName());
            if (!ecologyPoolRecord.insert()) {
                throw new GlobalRunTimeException("更新生态池积分失败");
            }

        } catch (Exception e) {
            log.error("生态池分配/扣除积分异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    /**
     * 执行减积分
     *
     * @param ecologyPoolIncreasePointsDTO
     */
    private void doIncreasePoints(EcologyPoolIncreasePointsDTO ecologyPoolIncreasePointsDTO) {
        RLock lock = redisson.getLock(RedisKeyEnum.ECOLOGY_POOL.getKey() + "_" + ecologyPoolIncreasePointsDTO.buildPkCode());
        try {
            if (!lock.tryLock(10, TimeUnit.SECONDS)) {
                log.error("操作频繁，请稍后重试");
                throw new GlobalRunTimeException("操作频繁，请稍后重试");
            }
            EcologyPool ecologyPool = ecologyPoolDao.getOneByTypeAndDaoIdUserId(ecologyPoolIncreasePointsDTO.getPoolType(), ecologyPoolIncreasePointsDTO.getLinkType(), ecologyPoolIncreasePointsDTO.getDaoId(), ecologyPoolIncreasePointsDTO.getUserId());
            if (Objects.nonNull(ecologyPool)) {

                ecologyPoolDao.increasePoints(ecologyPool.getId(), ecologyPoolIncreasePointsDTO.getLinkCount(), ecologyPool.getVersion());

                EcologyPoolRecord ecologyPoolRecord = new EcologyPoolRecord();
                ecologyPoolRecord.setLinkCount(ecologyPoolIncreasePointsDTO.getLinkCount());
                ecologyPoolRecord.setLinkType(ecologyPoolIncreasePointsDTO.getLinkType());
                ecologyPoolRecord.setBeforeLinkCount(ecologyPool.getLinkCount());
                ecologyPoolRecord.setAfterLinkCount(ecologyPool.getLinkCount().add(ecologyPoolIncreasePointsDTO.getLinkCount()));
                ecologyPoolRecord.setIsAdd(true);
                ecologyPoolRecord.setDaoId(ecologyPoolIncreasePointsDTO.getDaoId());
                ecologyPoolRecord.setUserId(ecologyPoolIncreasePointsDTO.getUserId());
                ecologyPoolRecord.setRelationId(ecologyPoolIncreasePointsDTO.getRelationId());
                ecologyPoolRecord.setPoolType(ecologyPoolIncreasePointsDTO.getPoolType());
                ecologyPoolRecord.setOperationType(ecologyPoolIncreasePointsDTO.getOperationType());
                ecologyPoolRecord.setFlowType(EcologyPoolFlowTypeEnum.IN_FLOW);
                ecologyPoolRecord.setSourcePoolType(ecologyPoolIncreasePointsDTO.getSourcePoolType());
                ecologyPoolRecord.setSourceDaoId(ecologyPoolIncreasePointsDTO.getSourceDaoId());
                ecologyPoolRecord.setSourceUserId(ecologyPoolIncreasePointsDTO.getSourceUserId());
                ecologyPoolRecord.setSourceRelationId(ecologyPoolIncreasePointsDTO.getSourceRelationId());
                ecologyPoolRecord.setTransactionUuid(ecologyPoolIncreasePointsDTO.getTransactionUuid());
                ecologyPoolRecord.setRemark(ecologyPoolIncreasePointsDTO.getRemark());
                ecologyPoolRecord.setActiveOperatorName(ecologyPoolIncreasePointsDTO.getActiveOperatorName());
                ecologyPoolRecord.setPassiveOperatorName(ecologyPoolIncreasePointsDTO.getPassiveOperatorName());
                if (!ecologyPoolRecord.insert()) {
                    throw new GlobalRunTimeException("更新生态池积分失败");
                }

            } else {
                ecologyPool = new EcologyPool();
                ecologyPool.setLinkCount(ecologyPoolIncreasePointsDTO.getLinkCount());
                ecologyPool.setLinkType(ecologyPoolIncreasePointsDTO.getLinkType());
                ecologyPool.setDaoId(ecologyPoolIncreasePointsDTO.getDaoId());
                ecologyPool.setUserId(ecologyPoolIncreasePointsDTO.getUserId());
                ecologyPool.setPoolType(ecologyPoolIncreasePointsDTO.getPoolType());
                ecologyPool.setVersion(1);
                ecologyPool.buildPkCode();
                if (!ecologyPool.insert()) {
                    throw new GlobalRunTimeException("更新生态池积分失败");
                }

                EcologyPoolRecord ecologyPoolRecord = new EcologyPoolRecord();
                ecologyPoolRecord.setLinkCount(ecologyPoolIncreasePointsDTO.getLinkCount());
                ecologyPoolRecord.setLinkType(ecologyPoolIncreasePointsDTO.getLinkType());
                ecologyPoolRecord.setBeforeLinkCount(BigDecimal.ZERO);
                ecologyPoolRecord.setAfterLinkCount(ecologyPoolIncreasePointsDTO.getLinkCount());
                ecologyPoolRecord.setIsAdd(true);
                ecologyPoolRecord.setDaoId(ecologyPoolIncreasePointsDTO.getDaoId());
                ecologyPoolRecord.setUserId(ecologyPoolIncreasePointsDTO.getUserId());
                ecologyPoolRecord.setRelationId(ecologyPoolIncreasePointsDTO.getRelationId());
                ecologyPoolRecord.setPoolType(ecologyPoolIncreasePointsDTO.getPoolType());
                ecologyPoolRecord.setOperationType(ecologyPoolIncreasePointsDTO.getOperationType());
                ecologyPoolRecord.setFlowType(EcologyPoolFlowTypeEnum.IN_FLOW);
                ecologyPoolRecord.setSourcePoolType(ecologyPoolIncreasePointsDTO.getSourcePoolType());
                ecologyPoolRecord.setSourceDaoId(ecologyPoolIncreasePointsDTO.getSourceDaoId());
                ecologyPoolRecord.setSourceUserId(ecologyPoolIncreasePointsDTO.getSourceUserId());
                ecologyPoolRecord.setSourceRelationId(ecologyPoolIncreasePointsDTO.getSourceRelationId());
                ecologyPoolRecord.setTransactionUuid(ecologyPoolIncreasePointsDTO.getTransactionUuid());
                ecologyPoolRecord.setRemark(ecologyPoolIncreasePointsDTO.getRemark());
                ecologyPoolRecord.setActiveOperatorName(ecologyPoolIncreasePointsDTO.getActiveOperatorName());
                ecologyPoolRecord.setPassiveOperatorName(ecologyPoolIncreasePointsDTO.getPassiveOperatorName());
                if (!ecologyPoolRecord.insert()) {
                    throw new GlobalRunTimeException("更新生态池积分失败");
                }

            }

        } catch (Exception e) {
            log.error("生态池分配/扣除积分异常", e);
            throw new GlobalRunTimeException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    /**
     * 校验服务中心/社区网点分配积分参数
     *
     * @param operationType
     * @param poolType
     * @param userId
     * @param linkCount
     * @param linkType
     */
    private List<EcologyPool> validateCommunityServiceCenterAllocatePoints(EcologyPoolOperationTypeEnum operationType, EcologyPoolTypeEnum poolType, Long userId, Long linkCount, EcologyPoolLinkTypeEnum linkType) {
        UserInfo userInfo = userInfoDao.getById(userId);
        Assert.notNull(userInfo, () -> new GlobalRunTimeException("用户不存在"));
        List<EcologyPool> ecologyPoolList = new ArrayList<>();
        EcologyPool ecologyPool = ecologyPoolDao.getByType(poolType, linkType);
        if (Objects.nonNull(ecologyPool)) {
            ecologyPoolList.add(ecologyPool);
        }
        ecologyPool = ecologyPoolDao.getByTypeAndDaoIdUserId(EcologyPoolTypeEnum.ACCOUNT, linkType, META_DAO_ID, userId);
        if (Objects.nonNull(ecologyPool)) {
            ecologyPoolList.add(ecologyPool);
        }
        if (Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode())) {
            validateEcologyPool(ecologyPoolList, poolType, linkCount, poolType.getDesc() + "积分不足");
        } else {
            validateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.ACCOUNT, linkCount, ErrorCode.ACCOUNT_ECOLOGY_NOT_ENOUGH.getMessage());
        }
        return ecologyPoolList;
    }

    /**
     * 执行校验服务中心/社区网点分配积分
     *
     * @param operationType
     * @param poolType
     * @param userId
     * @param linkCount
     * @param linkType
     * @param remark
     */
    private void doCommunityServiceCenterAllocatePoints(List<EcologyPool> ecologyPoolList, EcologyPoolOperationTypeEnum operationType, EcologyPoolTypeEnum poolType, Long userId, Long linkCount, EcologyPoolLinkTypeEnum linkType, String remark) {
        if (Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode())) {
            //扣减服务中心/社区网点生态池积分
            Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, poolType, BigDecimal.valueOf(linkCount));
            Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.ACCOUNT, BigDecimal.valueOf(linkCount), linkType, META_DAO_ID, userId);
            //添加变动记录
            doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(linkCount), linkType, operationType, remark);
        } else {
            //增加服务中心/社区网点生态池积分
            Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, poolType, BigDecimal.valueOf(linkCount), linkType, META_DAO_ID, null);
            Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.ACCOUNT, BigDecimal.valueOf(linkCount));
            //添加变动记录
            doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(linkCount), linkType, operationType, remark);
        }
    }

    /**
     * 校验创建排行榜参数
     *
     * @param request
     */
    private Map<EcologyPoolLinkTypeEnum, BigDecimal> validateCreateDaoCommunityServiceRankConf(EcologyPoolCreateDaoCommunityServiceRankConfRpcRequest request) {
        Date startTime = DateUtil.truncate(DateUtil.beginOfDay(request.getStartTime()), DateField.SECOND);
        Date endTime = DateUtil.truncate(DateUtil.endOfDay(request.getEndTime()), DateField.SECOND);
        Assert.isFalse(startTime.after(endTime), () -> new GlobalRunTimeException(ErrorCode.START_TIME_AFTER_END_TIME));
        //region 查找排行榜最大结束时间
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getMaxEndTime(request.getRankType(), request.getDaoId());
        if (Objects.nonNull(ecologyPoolCommunityServiceRankConf)) {
            Assert.isTrue(request.getStartTime().after(ecologyPoolCommunityServiceRankConf.getEndTime()), () -> new GlobalRunTimeException(ErrorCode.START_TIME_AFTER_MAX_END_TIME));
        } else {
            Assert.isTrue(request.getStartTime().after(DateTime.now()), () -> new GlobalRunTimeException(ErrorCode.THE_START_TIME_CANNOT_BE_EARLIER_THAN_THE_CURRENT_TIME));
        }
        //endregion
        //region 校验榜单关联
        validateRankRelation(request.getRelationList(), request.getDaoId(), Boolean.TRUE);
        //endregion
        //region 校验收益
        return validateRankPrize(request.getIncomeList(), request.getDaoId());
        //endregion
    }

    /**
     * 校验榜单关联
     *
     * @param relationList
     * @param daoId
     */
    private void validateRankRelation(List<EcologyPoolCreateCommunityServiceRankRelationConfRequest> relationList, Long daoId, Boolean require) {
        if (CollectionUtil.isEmpty(relationList)) {
            if (require) {
                throw new GlobalRunTimeException("关联不能为空");
            } else {
                return;
            }
        }
        relationList.forEach(relation -> {
            Assert.notNull(relation.getRelationType(), () -> new GlobalRunTimeException("关联类型不能为空"));
            Assert.notNull(relation.getRelationId(), () -> new GlobalRunTimeException("关联ID不能为空"));
        });
        Map<EcologyPoolRelationTypeEnum, List<EcologyPoolCreateCommunityServiceRankRelationConfRequest>> relationMap = relationList.stream().collect(Collectors.groupingBy(EcologyPoolCreateCommunityServiceRankRelationConfRequest::getRelationType));
        List<EcologyPoolCreateCommunityServiceRankRelationConfRequest> collectionRelationList = relationMap.get(EcologyPoolRelationTypeEnum.COLLECTION);
        if (CollectionUtil.isNotEmpty(collectionRelationList)) {
            List<Long> collectionIdList = collectionRelationList.stream().map(EcologyPoolCreateCommunityServiceRankRelationConfRequest::getRelationId).distinct().collect(Collectors.toList());
            List<DigitalCollection> collectionList = digitalCollectionDao.getByIds(collectionIdList);
            if (CollectionUtil.isEmpty(collectionList)) {
                throw new GlobalRunTimeException("藏品不存在");
            }
            Map<Long, DigitalCollection> collectionMap = collectionList.stream().collect(Collectors.toMap(DigitalCollection::getId, Function.identity()));
            for (Long collectionId : collectionIdList) {
                DigitalCollection collection = collectionMap.get(collectionId);
                if (Objects.isNull(collection)) {
                    throw new GlobalRunTimeException("藏品不存在");
                }
                if (!Objects.equals(META_DAO_ID, daoId) && !Objects.equals(collection.getUserCreatorId(), daoId)) {
                    throw new GlobalRunTimeException("藏品不属于当前品牌");
                }
            }
        }
    }

    /**
     * 校验收益
     */
    private Map<EcologyPoolLinkTypeEnum, BigDecimal> validateRankPrize(List<EcologyPoolCreateDaoCommunityServiceRankConfIncomeRequest> incomeList, Long daoId) {
        Assert.notEmpty(incomeList, () -> new GlobalRunTimeException(ErrorCode.INCOME_NAME_NOT_EMPTY));
        Map<EcologyPoolLinkTypeEnum, BigDecimal> totalPrizeMap = new HashMap<>();
        Integer startRank = 0;
        Integer index = 1;
        for (EcologyPoolCreateDaoCommunityServiceRankConfIncomeRequest income : incomeList) {
            Assert.notBlank(income.getIncomeName(), () -> new GlobalRunTimeException(ErrorCode.INCOME_NAME_NOT_EMPTY));
            Assert.notNull(income.getStartRank(), () -> new GlobalRunTimeException(ErrorCode.START_RANK_NOT_NULL));
            Assert.notNull(income.getEndRank(), () -> new GlobalRunTimeException(ErrorCode.END_RANK_NOT_NULL));
            Assert.isTrue(income.getStartRank() < income.getEndRank(), () -> new GlobalRunTimeException(ErrorCode.START_RANK_LT_END_RANK));
            Integer finalIndex = index;
            Integer finalStartRank = startRank;
            Assert.isTrue(Objects.equals(startRank, income.getStartRank()), () -> new GlobalRunTimeException("第" + finalIndex + "行排名区间应大于" + finalStartRank));
            Assert.notEmpty(income.getPrizeList(), () -> new GlobalRunTimeException("奖励不能为空"));
            income.getPrizeList().forEach(prize -> {
                Assert.notNull(prize.getPrizeType(), () -> new GlobalRunTimeException("奖励类型不能为空"));
                Assert.notNull(prize.getPrizeCount(), () -> new GlobalRunTimeException("奖励数量不能为空"));
                Assert.isTrue(prize.getPrizeCount().compareTo(BigDecimal.ZERO) > 0, () -> new GlobalRunTimeException("奖励必须大于0"));
                //计算总收益
                for (int i = income.getStartRank() + 1; i <= income.getEndRank(); i++) {
                    BigDecimal prizeCount = totalPrizeMap.get(prize.getPrizeType());
                    prizeCount = (Objects.nonNull(prizeCount) ? prizeCount : BigDecimal.ZERO).add(prize.getPrizeCount());
                    totalPrizeMap.put(prize.getPrizeType(), prizeCount);
                }
            });
            if (Objects.nonNull(income.getCondition())) {
                EcologyPoolCreateDaoCommunityServiceRankConfIncomeConditionRequest condition = income.getCondition();
                if (Objects.nonNull(condition.getNewUserCountThreshold())) {
                    Assert.isTrue(condition.getNewUserCountThreshold() >= 0, () -> new GlobalRunTimeException(ErrorCode.NEW_USER_COUNT_NOT_LT_ZERO));
                }
                if (Objects.nonNull(condition.getNewEcologySmeltingThreshold())) {
                    Assert.isTrue(condition.getNewEcologySmeltingThreshold().compareTo(BigDecimal.ZERO) >= 0, () -> new GlobalRunTimeException(ErrorCode.NEW_ECOLOGY_SMELTING_NOT_LT_ZERO));
                }
            }
            startRank = income.getEndRank();
            index = index + 1;
        }
        for (Map.Entry<EcologyPoolLinkTypeEnum, BigDecimal> entry : totalPrizeMap.entrySet()) {
            if (entry.getValue().compareTo(BigDecimal.ZERO) > 0) {
                if (Objects.equals(EcologyPoolLinkTypeEnum.POINTS.getCode(), entry.getKey().getCode())) {
                    EcologyPool ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, EcologyPoolLinkTypeEnum.POINTS, daoId);
                    if (Objects.isNull(ecologyPool)) {
                        throw new GlobalRunTimeException("积分不足");
                    }
                    if (ecologyPool.getLinkCount().compareTo(entry.getValue()) < 0) {
                        throw new GlobalRunTimeException("积分不足");
                    }
                }
            }
        }
        return totalPrizeMap;
    }

    /**
     * 执行创建排行榜
     *
     * @param request
     */
    private void doCreateDaoCommunityServiceRankConf(EcologyPoolCreateDaoCommunityServiceRankConfRpcRequest request, Map<EcologyPoolLinkTypeEnum, BigDecimal> totalPrizeMap) {
        Date startTime = DateUtil.truncate(DateUtil.beginOfDay(request.getStartTime()), DateField.SECOND);
        Date endTime = DateUtil.truncate(DateUtil.endOfDay(request.getEndTime()), DateField.SECOND);
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = new EcologyPoolCommunityServiceRankConf();
        ecologyPoolCommunityServiceRankConf.setDaoId(request.getDaoId());
        ecologyPoolCommunityServiceRankConf.setRankName(request.getRankName());
        ecologyPoolCommunityServiceRankConf.setRankType(request.getRankType());
        ecologyPoolCommunityServiceRankConf.setNewUserCountThreshold(request.getNewUserCountThreshold());
        ecologyPoolCommunityServiceRankConf.setNewEcologySmeltingThreshold(request.getNewEcologySmeltingThreshold());
        ecologyPoolCommunityServiceRankConf.setStartTime(startTime);
        ecologyPoolCommunityServiceRankConf.setEndTime(endTime);
        ecologyPoolCommunityServiceRankConf.setActivityRule(request.getActivityRule());
        ecologyPoolCommunityServiceRankConf.setTopImage(request.getTopImage());
        ecologyPoolCommunityServiceRankConf.setStatus(Boolean.FALSE);
        ecologyPoolCommunityServiceRankConf.setJoinRankCount(0);
        ecologyPoolCommunityServiceRankConf.setApprovalStatus(EcologyPoolCommunityServiceRankApprovalStatusEnum.IN_APPROVAL);
        ecologyPoolCommunityServiceRankConf.setAutoSettle(Boolean.TRUE);
        ecologyPoolCommunityServiceRankConf.setSettled(Boolean.FALSE);
        ecologyPoolCommunityServiceRankConf.insert();

        if (CollectionUtil.isNotEmpty(request.getRelationList())) {
            request.getRelationList().forEach(relation -> {
                EcologyPoolRelationConditionBind ecologyPoolRelationConditionBind = new EcologyPoolRelationConditionBind();
                ecologyPoolRelationConditionBind.setBindType(EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK);
                ecologyPoolRelationConditionBind.setBindId(ecologyPoolCommunityServiceRankConf.getId());
                ecologyPoolRelationConditionBind.setRelationType(relation.getRelationType());
                ecologyPoolRelationConditionBind.setRelationId(relation.getRelationId());
                ecologyPoolRelationConditionBind.insert();
            });
        }

        Long sort = 1L;
        for (EcologyPoolCreateDaoCommunityServiceRankConfIncomeRequest rankConfIncomeRequest : request.getIncomeList()) {
            EcologyPoolCommunityServiceRankIncomeConf ecologyPoolCommunityServiceRankIncomeConf = new EcologyPoolCommunityServiceRankIncomeConf();
            ecologyPoolCommunityServiceRankIncomeConf.setEcologyPoolCommunityServiceRankConfId(ecologyPoolCommunityServiceRankConf.getId());
            ecologyPoolCommunityServiceRankIncomeConf.setIncomeName(rankConfIncomeRequest.getIncomeName());
            ecologyPoolCommunityServiceRankIncomeConf.setStartRank(rankConfIncomeRequest.getStartRank());
            ecologyPoolCommunityServiceRankIncomeConf.setEndRank(rankConfIncomeRequest.getEndRank());
            ecologyPoolCommunityServiceRankIncomeConf.setPrizeRatio(0);
            ecologyPoolCommunityServiceRankIncomeConf.setSort(sort);
            ecologyPoolCommunityServiceRankIncomeConf.insert();

            rankConfIncomeRequest.getPrizeList().forEach(prize -> {
                EcologyPoolPrize ecologyPoolPrize = new EcologyPoolPrize();
                ecologyPoolPrize.setBindType(EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK_INCOME);
                ecologyPoolPrize.setBindId(ecologyPoolCommunityServiceRankIncomeConf.getId());
                ecologyPoolPrize.setLinkType(EcologyPoolLinkTypeEnum.POINTS);
                ecologyPoolPrize.setLinkCount(prize.getPrizeCount());
                ecologyPoolPrize.setRemainCount(prize.getPrizeCount());
                ecologyPoolPrize.setLinkNumber(1L);
                ecologyPoolPrize.setRemainNumber(1L);
                ecologyPoolPrize.setVersion(1);
                ecologyPoolPrize.insert();
            });

            EcologyPoolCreateDaoCommunityServiceRankConfIncomeConditionRequest condition = rankConfIncomeRequest.getCondition();
            if (Objects.nonNull(condition)) {
                if (Objects.nonNull(condition.getNewEcologySmeltingThreshold()) || Objects.nonNull(condition.getNewUserCountThreshold())) {
                    EcologyPoolCommunityServiceRankIncomeConditionConf ecologyPoolCommunityServiceRankIncomeConditionConf = new EcologyPoolCommunityServiceRankIncomeConditionConf();
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setEcologyPoolCommunityServiceRankConfId(ecologyPoolCommunityServiceRankConf.getId());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setEcologyPoolCommunityServiceRankIncomeConfId(ecologyPoolCommunityServiceRankIncomeConf.getId());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setNewEcologySmeltingThreshold(condition.getNewEcologySmeltingThreshold());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setNewUserCountThreshold(condition.getNewUserCountThreshold());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.insert();
                }
            }
            sort = sort + 1L;
        }
        //region 保存奖励
        BigDecimal prizeCount = totalPrizeMap.get(EcologyPoolLinkTypeEnum.POINTS);
        if (Objects.nonNull(prizeCount) && prizeCount.compareTo(BigDecimal.ZERO) > 0) {
            EcologyPoolPrize ecologyPoolPrize = new EcologyPoolPrize();
            ecologyPoolPrize.setBindType(EcologyPoolPrizeBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK);
            ecologyPoolPrize.setBindId(ecologyPoolCommunityServiceRankConf.getId());
            ecologyPoolPrize.setLinkType(EcologyPoolLinkTypeEnum.POINTS);
            ecologyPoolPrize.setLinkCount(prizeCount);
            ecologyPoolPrize.setRemainCount(prizeCount);
            ecologyPoolPrize.setLinkNumber(1L);
            ecologyPoolPrize.setRemainNumber(1L);
            ecologyPoolPrize.setVersion(1);
            ecologyPoolPrize.insert();
            //region 扣减生态池积分
            EcologyPoolReducePointsDTO ecologyPoolReducePointsDTO = EcologyPoolReducePointsDTO.builder()
                    .linkCount(prizeCount)
                    .linkType(EcologyPoolLinkTypeEnum.POINTS)
                    .daoId(request.getDaoId())
                    .poolType(EcologyPoolTypeEnum.BRAND)
                    .operationType(EcologyPoolOperationTypeEnum.PLUS)
                    .sourcePoolType(Objects.equals(request.getRankType(), EcologyPoolCommunityServiceRankTypeEnum.COMMUNITY) ? EcologyPoolTypeEnum.COMMUNITY_NETWORK_RANK : EcologyPoolTypeEnum.SERVICE_CENTER_RANK)
                    .sourceDaoId(request.getDaoId())
                    .sourceRelationId(ecologyPoolCommunityServiceRankConf.getId())
                    .transactionUuid(IdUtil.simpleUUID())
                    .activeOperatorName("品牌生态池")
                    .passiveOperatorName("排行榜")
                    .build();
            this.reducePoints(ecologyPoolReducePointsDTO);
            //endregion
        }
        //endregion
    }

    /**
     * 校验创建排行榜参数
     *
     * @param request
     */
    private void validateCreateCommunityServiceRankConf(EcologyPoolCreateCommunityServiceRankConfRequest request) {
        Assert.isFalse(request.getStartTime().after(request.getEndTime()), () -> new GlobalRunTimeException(ErrorCode.START_TIME_AFTER_END_TIME));
        //region 查找排行榜最大结束时间
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = ecologyPoolCommunityServiceRankConfDao.getMaxEndTime(request.getRankType(), META_DAO_ID);
        if (Objects.nonNull(ecologyPoolCommunityServiceRankConf)) {
            Assert.isTrue(request.getStartTime().after(ecologyPoolCommunityServiceRankConf.getEndTime()), () -> new GlobalRunTimeException(ErrorCode.START_TIME_AFTER_MAX_END_TIME));
        } else {
            Assert.isTrue(request.getStartTime().after(DateTime.now()), () -> new GlobalRunTimeException(ErrorCode.THE_START_TIME_CANNOT_BE_EARLIER_THAN_THE_CURRENT_TIME));
        }
        //endregion
        //region 校验榜单关联
        validateRankRelation(request.getRelationList(), META_DAO_ID, Boolean.FALSE);
        //endregion
        //region 校验收益
        Assert.notEmpty(request.getIncomeList(), () -> new GlobalRunTimeException(ErrorCode.INCOME_NAME_NOT_EMPTY));
        Integer startRank = 0;
        Integer index = 1;
        for (EcologyPoolCreateCommunityServiceRankConfIncomeRequest income : request.getIncomeList()) {
            Assert.notBlank(income.getIncomeName(), () -> new GlobalRunTimeException(ErrorCode.INCOME_NAME_NOT_EMPTY));
            Assert.notNull(income.getStartRank(), () -> new GlobalRunTimeException(ErrorCode.START_RANK_NOT_NULL));
            Assert.notNull(income.getEndRank(), () -> new GlobalRunTimeException(ErrorCode.END_RANK_NOT_NULL));
            Assert.isTrue(income.getStartRank() < income.getEndRank(), () -> new GlobalRunTimeException(ErrorCode.START_RANK_LT_END_RANK));
            Integer finalIndex = index;
            Integer finalStartRank = startRank;
            Assert.isTrue(Objects.equals(startRank, income.getStartRank()), () -> new GlobalRunTimeException("第" + finalIndex + "行排名区间应大于" + finalStartRank));
            Assert.notNull(income.getPrizeRatio(), () -> new GlobalRunTimeException(ErrorCode.PRIZE_RATIO_NOT_NULL));
            Assert.isTrue(income.getPrizeRatio() >= 0, () -> new GlobalRunTimeException(ErrorCode.PRIZE_RATIO_NOT_LT_ZERO));
            Assert.isTrue(income.getPrizeRatio() <= 100, () -> new GlobalRunTimeException(ErrorCode.PRIZE_RATIO_NOT_GT_HUNDRED));
            if (Objects.nonNull(income.getCondition())) {
                EcologyPoolCreateCommunityServiceRankConfIncomeConditionRequest condition = income.getCondition();
                if (Objects.nonNull(condition.getNewUserCountThreshold())) {
                    Assert.isTrue(condition.getNewUserCountThreshold() >= 0, () -> new GlobalRunTimeException(ErrorCode.NEW_USER_COUNT_NOT_LT_ZERO));
                }
                if (Objects.nonNull(condition.getNewEcologySmeltingThreshold())) {
                    Assert.isTrue(condition.getNewEcologySmeltingThreshold().compareTo(BigDecimal.ZERO) >= 0, () -> new GlobalRunTimeException(ErrorCode.NEW_ECOLOGY_SMELTING_NOT_LT_ZERO));
                }
            }
            startRank = income.getEndRank();
            index = index + 1;
        }
        //endregion
    }

    /**
     * 执行创建排行榜
     *
     * @param request
     */
    private void doCreateCommunityServiceRankConf(EcologyPoolCreateCommunityServiceRankConfRequest request) {
        EcologyPoolCommunityServiceRankConf ecologyPoolCommunityServiceRankConf = new EcologyPoolCommunityServiceRankConf();
        ecologyPoolCommunityServiceRankConf.setDaoId(META_DAO_ID);
        ecologyPoolCommunityServiceRankConf.setRankName(request.getRankName());
        ecologyPoolCommunityServiceRankConf.setRankType(request.getRankType());
        ecologyPoolCommunityServiceRankConf.setNewUserCountThreshold(request.getNewUserCountThreshold());
        ecologyPoolCommunityServiceRankConf.setNewEcologySmeltingThreshold(request.getNewEcologySmeltingThreshold());
        ecologyPoolCommunityServiceRankConf.setStartTime(request.getStartTime());
        ecologyPoolCommunityServiceRankConf.setEndTime(request.getEndTime());
        ecologyPoolCommunityServiceRankConf.setActivityRule(request.getActivityRule());
        ecologyPoolCommunityServiceRankConf.setTopImage(request.getTopImage());
        ecologyPoolCommunityServiceRankConf.setStatus(Boolean.FALSE);
        ecologyPoolCommunityServiceRankConf.setJoinRankCount(0);
        ecologyPoolCommunityServiceRankConf.setApprovalStatus(EcologyPoolCommunityServiceRankApprovalStatusEnum.APPROVAL_SUCCESS);
        ecologyPoolCommunityServiceRankConf.setAutoSettle(Boolean.FALSE);
        ecologyPoolCommunityServiceRankConf.setSettled(Boolean.TRUE);
        ecologyPoolCommunityServiceRankConf.insert();

        //region 保存关联
        if (CollectionUtil.isNotEmpty(request.getRelationList())) {
            request.getRelationList().forEach(relation -> {
                EcologyPoolRelationConditionBind ecologyPoolRelationConditionBind = new EcologyPoolRelationConditionBind();
                ecologyPoolRelationConditionBind.setBindType(EcologyPoolRelationConditionBindTypeEnum.COMMUNITY_SERVICE_CENTER_RANK);
                ecologyPoolRelationConditionBind.setBindId(ecologyPoolCommunityServiceRankConf.getId());
                ecologyPoolRelationConditionBind.setRelationType(relation.getRelationType());
                ecologyPoolRelationConditionBind.setRelationId(relation.getRelationId());
                ecologyPoolRelationConditionBind.insert();
            });
        }
        //endregion

        Long sort = 1L;
        for (EcologyPoolCreateCommunityServiceRankConfIncomeRequest rankConfIncomeRequest : request.getIncomeList()) {
            EcologyPoolCommunityServiceRankIncomeConf ecologyPoolCommunityServiceRankIncomeConf = new EcologyPoolCommunityServiceRankIncomeConf();
            ecologyPoolCommunityServiceRankIncomeConf.setEcologyPoolCommunityServiceRankConfId(ecologyPoolCommunityServiceRankConf.getId());
            ecologyPoolCommunityServiceRankIncomeConf.setIncomeName(rankConfIncomeRequest.getIncomeName());
            ecologyPoolCommunityServiceRankIncomeConf.setStartRank(rankConfIncomeRequest.getStartRank());
            ecologyPoolCommunityServiceRankIncomeConf.setEndRank(rankConfIncomeRequest.getEndRank());
            ecologyPoolCommunityServiceRankIncomeConf.setPrizeRatio(rankConfIncomeRequest.getPrizeRatio());
            ecologyPoolCommunityServiceRankIncomeConf.setSort(sort);
            ecologyPoolCommunityServiceRankIncomeConf.insert();

            EcologyPoolCreateCommunityServiceRankConfIncomeConditionRequest condition = rankConfIncomeRequest.getCondition();
            if (Objects.nonNull(condition)) {
                if (Objects.nonNull(condition.getNewEcologySmeltingThreshold()) || Objects.nonNull(condition.getNewUserCountThreshold())) {
                    EcologyPoolCommunityServiceRankIncomeConditionConf ecologyPoolCommunityServiceRankIncomeConditionConf = new EcologyPoolCommunityServiceRankIncomeConditionConf();
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setEcologyPoolCommunityServiceRankConfId(ecologyPoolCommunityServiceRankConf.getId());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setEcologyPoolCommunityServiceRankIncomeConfId(ecologyPoolCommunityServiceRankIncomeConf.getId());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setNewEcologySmeltingThreshold(condition.getNewEcologySmeltingThreshold());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.setNewUserCountThreshold(condition.getNewUserCountThreshold());
                    ecologyPoolCommunityServiceRankIncomeConditionConf.insert();
                }
            }
            sort = sort + 1L;
        }
    }

    /**
     * 执行官方生态池积分配/扣除
     */
    private void doOfficialAllocatePoints(List<EcologyPool> ecologyPoolList, EcologyPoolOperationTypeEnum operationType, Long excellentBrandCount, Long serviceCenterCount, Long communityNetworkCount, EcologyPoolLinkTypeEnum linkType, String remark) {
        if (Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode())) {
            //region 增加优秀生态池积分
            if (excellentBrandCount > 0) {
                //扣减官方生态池积分
                Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.OFFICIAL, BigDecimal.valueOf(excellentBrandCount));
                Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.EXCELLENT_BRAND, BigDecimal.valueOf(excellentBrandCount), linkType, META_DAO_ID, null);
                //添加变动记录
                doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(excellentBrandCount), linkType, operationType, remark);
            }
            //endregion
            //region 增加服务中心池积分
            if (serviceCenterCount > 0) {
                //扣减官方生态池积分
                Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.OFFICIAL, BigDecimal.valueOf(serviceCenterCount));
                Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.SERVICE_CENTER, BigDecimal.valueOf(serviceCenterCount), linkType, META_DAO_ID, null);
                //添加变动记录
                doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(serviceCenterCount), linkType, operationType, remark);
            }
            //endregion
            //region 增加社区网点池积分
            if (communityNetworkCount > 0) {
                //扣减官方生态池积分
                Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.OFFICIAL, BigDecimal.valueOf(communityNetworkCount));
                Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.COMMUNITY_NETWORK, BigDecimal.valueOf(communityNetworkCount), linkType, META_DAO_ID, null);
                //添加变动记录
                doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(communityNetworkCount), linkType, operationType, remark);
            }
            //endregion
        } else {
            //region 扣减优秀生态池积分
            if (excellentBrandCount > 0) {
                //增加官方生态池积分
                Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.OFFICIAL, BigDecimal.valueOf(excellentBrandCount), linkType, META_DAO_ID, null);
                Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.EXCELLENT_BRAND, BigDecimal.valueOf(excellentBrandCount));
                //添加变动记录
                doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(excellentBrandCount), linkType, operationType, remark);
            }
            //endregion
            //region 扣减服务中心池积分
            if (serviceCenterCount > 0) {
                //增加官方生态池积分
                Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.OFFICIAL, BigDecimal.valueOf(serviceCenterCount), linkType, META_DAO_ID, null);
                Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.SERVICE_CENTER, BigDecimal.valueOf(serviceCenterCount));
                //添加变动记录
                doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(serviceCenterCount), linkType, operationType, remark);
            }
            //endregion
            //region 扣减社区网点池积分
            if (communityNetworkCount > 0) {
                //增加官方生态池积分
                Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.OFFICIAL, BigDecimal.valueOf(communityNetworkCount), linkType, META_DAO_ID, null);
                Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.COMMUNITY_NETWORK, BigDecimal.valueOf(communityNetworkCount));
                //添加变动记录
                doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(communityNetworkCount), linkType, operationType, remark);
            }
            //endregion
        }
    }

    /**
     * 添加变动记录
     *
     * @param sourceEcologyPoolId
     * @param targetEcologyPoolId
     * @param linkCount
     * @param linkType
     * @param operationType
     * @param remark
     */
    private void doNewEcologyPoolRecord(Long sourceEcologyPoolId,
                                        Long targetEcologyPoolId,
                                        BigDecimal linkCount,
                                        EcologyPoolLinkTypeEnum linkType,
                                        EcologyPoolOperationTypeEnum operationType,
                                        String remark) {
        EcologyPool sourceEcologyPool = ecologyPoolDao.getById(sourceEcologyPoolId);
        EcologyPool targetEcologyPool = ecologyPoolDao.getById(targetEcologyPoolId);
        String activeOperatorName = Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode()) ? findOperatorName(sourceEcologyPool) : findOperatorName((targetEcologyPool));
        String passiveOperatorName = Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode()) ? findOperatorName(targetEcologyPool) : findOperatorName((sourceEcologyPool));
        //出帐记录和入帐记录的事务编码相同，方便排查问题
        String uuid = IdUtil.simpleUUID();
        //region 出账记录
        EcologyPoolRecord sourceEcologyPoolRecord = new EcologyPoolRecord();
        sourceEcologyPoolRecord.setLinkCount(linkCount);
        sourceEcologyPoolRecord.setLinkType(linkType);
        sourceEcologyPoolRecord.setBeforeLinkCount(sourceEcologyPool.getLinkCount().add(linkCount));
        sourceEcologyPoolRecord.setAfterLinkCount(sourceEcologyPool.getLinkCount());
        sourceEcologyPoolRecord.setIsAdd(false);
        sourceEcologyPoolRecord.setDaoId(sourceEcologyPool.getDaoId());
        sourceEcologyPoolRecord.setUserId(sourceEcologyPool.getUserId());
        sourceEcologyPoolRecord.setPoolType(sourceEcologyPool.getPoolType());
        sourceEcologyPoolRecord.setOperationType(operationType);
        sourceEcologyPoolRecord.setFlowType(EcologyPoolFlowTypeEnum.OUT_FLOW);
        sourceEcologyPoolRecord.setSourcePoolType(targetEcologyPool.getPoolType());
        sourceEcologyPoolRecord.setSourceDaoId(targetEcologyPool.getDaoId());
        sourceEcologyPoolRecord.setSourceUserId(targetEcologyPool.getUserId());
        sourceEcologyPoolRecord.setTransactionUuid(uuid);
        sourceEcologyPoolRecord.setRemark(remark);
        sourceEcologyPoolRecord.setActiveOperatorName(activeOperatorName);
        sourceEcologyPoolRecord.setPassiveOperatorName(passiveOperatorName);
        if (!sourceEcologyPoolRecord.insert()) {
            throw new GlobalRunTimeException("更新生态池积分失败");
        }
        //endregion
        //region 入账记录
        EcologyPoolRecord targetEcologyPoolRecord = new EcologyPoolRecord();
        targetEcologyPoolRecord.setLinkCount(linkCount);
        targetEcologyPoolRecord.setLinkType(linkType);
        targetEcologyPoolRecord.setBeforeLinkCount(targetEcologyPool.getLinkCount().subtract(linkCount));
        targetEcologyPoolRecord.setAfterLinkCount(targetEcologyPool.getLinkCount());
        targetEcologyPoolRecord.setIsAdd(true);
        targetEcologyPoolRecord.setDaoId(targetEcologyPool.getDaoId());
        targetEcologyPoolRecord.setUserId(targetEcologyPool.getUserId());
        targetEcologyPoolRecord.setPoolType(targetEcologyPool.getPoolType());
        targetEcologyPoolRecord.setOperationType(operationType);
        targetEcologyPoolRecord.setFlowType(EcologyPoolFlowTypeEnum.IN_FLOW);
        targetEcologyPoolRecord.setSourcePoolType(sourceEcologyPool.getPoolType());
        targetEcologyPoolRecord.setSourceDaoId(sourceEcologyPool.getDaoId());
        targetEcologyPoolRecord.setSourceUserId(sourceEcologyPool.getUserId());
        targetEcologyPoolRecord.setTransactionUuid(uuid);
        targetEcologyPoolRecord.setRemark(remark);
        targetEcologyPoolRecord.setActiveOperatorName(activeOperatorName);
        targetEcologyPoolRecord.setPassiveOperatorName(passiveOperatorName);
        if (!targetEcologyPoolRecord.insert()) {
            throw new GlobalRunTimeException("更新生态池积分失败");
        }
        //endregion
    }

    /**
     * 获取操作方
     *
     * @param ecologyPool
     * @return
     */
    private String findOperatorName(EcologyPool ecologyPool) {
        String operatorName = ecologyPool.getPoolType().getDesc();
        if (Objects.equals(ecologyPool.getPoolType().getCode(), EcologyPoolTypeEnum.BRAND.getCode())) {
            if (Objects.nonNull(ecologyPool.getDaoId())) {
                UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(ecologyPool.getDaoId());
                if (Objects.nonNull(userCreatorInfo)) {
                    operatorName = userCreatorInfo.getDaoName();
                }
            }
        }
        if (Objects.equals(ecologyPool.getPoolType().getCode(), EcologyPoolTypeEnum.ACCOUNT.getCode())) {
            if (Objects.nonNull(ecologyPool.getUserId())) {
                UserInfo userInfo = userInfoDao.getById(ecologyPool.getUserId());
                if (Objects.nonNull(userInfo)) {
                    operatorName = userInfo.getNickName();
                }
            }
        }
        return operatorName;
    }

    /**
     * 分配积分
     *
     * @param ecologyPoolList
     * @param poolType
     * @param linkCount
     */
    private Long doPlusUpdateEcologyPool(List<EcologyPool> ecologyPoolList, EcologyPoolTypeEnum poolType, BigDecimal linkCount, EcologyPoolLinkTypeEnum linkType, Long daoId, Long userId) {
        Optional<EcologyPool> optional = ecologyPoolList.stream().filter(pool -> Objects.equals(pool.getPoolType().getCode(), poolType.getCode())).findFirst();
        if (optional.isPresent()) {
            EcologyPool ecologyPool = optional.get();
            ecologyPoolDao.increasePoints(ecologyPool.getId(), linkCount, ecologyPool.getVersion());
            ecologyPool.setVersion(ecologyPool.getVersion() + 1);
            return ecologyPool.getId();
        } else {
            EcologyPool ecologyPool = new EcologyPool();
            ecologyPool.setLinkCount(linkCount);
            ecologyPool.setLinkType(linkType);
            if (Objects.nonNull(daoId)) {
                ecologyPool.setDaoId(daoId);
            }
            if (Objects.nonNull(userId)) {
                ecologyPool.setUserId(userId);
            }
            ecologyPool.setPoolType(poolType);
            ecologyPool.setVersion(1);
            ecologyPool.buildPkCode();
            if (!ecologyPool.insert()) {
                throw new GlobalRunTimeException("更新生态池积分失败");
            }
            ecologyPoolList.add(ecologyPool);
            return ecologyPool.getId();
        }
    }

    /**
     * 扣减加分
     *
     * @param ecologyPoolList
     * @param poolType
     * @param linkCount
     */
    private Long doReduceUpdateEcologyPool(List<EcologyPool> ecologyPoolList, EcologyPoolTypeEnum poolType, BigDecimal linkCount) {
        Optional<EcologyPool> optional = ecologyPoolList.stream().filter(pool -> Objects.equals(pool.getPoolType().getCode(), poolType.getCode())).findFirst();
        if (optional.isPresent()) {
            EcologyPool ecologyPool = optional.get();
            ecologyPoolDao.reducePoints(ecologyPool.getId(), linkCount, ecologyPool.getVersion());
            ecologyPool.setVersion(ecologyPool.getVersion() + 1);
            return ecologyPool.getId();
        } else {
            throw new GlobalRunTimeException("更新生态池积分失败");
        }
    }

    /**
     * 校验官方生态池分配/扣除积分参数
     */
    private List<EcologyPool> validateOfficialAllocatePoints(EcologyPoolOperationTypeEnum operationType, Long excellentBrandCount, Long serviceCenterCount, Long communityNetworkCount, EcologyPoolLinkTypeEnum linkType) {
        Long total = excellentBrandCount + serviceCenterCount + communityNetworkCount;
        //region 校验分配/扣除积分是否全为0
        if (Objects.equals(total, 0L)) {
            if (Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode())) {
                throw new GlobalRunTimeException("分配积分不能全为0");
            } else {
                throw new GlobalRunTimeException("扣除积分不能全为0");
            }
        }
        //region 校验分配/扣除积分是否全为0
        List<EcologyPoolTypeEnum> types = new ArrayList<>();
        types.add(EcologyPoolTypeEnum.OFFICIAL);
        types.add(EcologyPoolTypeEnum.EXCELLENT_BRAND);
        types.add(EcologyPoolTypeEnum.SERVICE_CENTER);
        types.add(EcologyPoolTypeEnum.COMMUNITY_NETWORK);
        List<EcologyPool> ecologyPoolList = ecologyPoolDao.getListByTypes(types, linkType);
        if (Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode())) {
            //region 分配时校验官方生态池积分
            validateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.OFFICIAL, total, ErrorCode.OFFICIAL_ECOLOGY_NOT_ENOUGH.getMessage());
            //endregion 分配时校验官方生态池积分
        } else {
            if (excellentBrandCount > 0L) {
                //region 扣除时校验优秀生态池积分
                validateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.EXCELLENT_BRAND, excellentBrandCount, ErrorCode.EXCELLENT_BRAND_ECOLOGY_NOT_ENOUGH.getMessage());
                //endregion 扣除时校验优秀生态池积分
            }
            if (serviceCenterCount > 0L) {
                //region 扣除时校验服务中心池积分
                validateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.SERVICE_CENTER, serviceCenterCount, ErrorCode.SERVICE_CENTER_ECOLOGY_NOT_ENOUGH.getMessage());
                //endregion 扣除时校验服务中心池积分
            }
            if (communityNetworkCount > 0L) {
                //region 扣除时校验社区网点池积分
                validateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.COMMUNITY_NETWORK, communityNetworkCount, ErrorCode.COMMUNITY_NETWORK_ECOLOGY_NOT_ENOUGH.getMessage());
                //endregion 扣除时校验社区网点池积分
            }
        }
        return ecologyPoolList;
    }

    /**
     * 校验生态池数据
     *
     * @param ecologyPoolList
     * @param poolType
     * @param linkCount
     * @param errorMessage
     */
    private void validateEcologyPool(List<EcologyPool> ecologyPoolList, EcologyPoolTypeEnum poolType, Long linkCount, String errorMessage) {
        if (CollectionUtil.isEmpty(ecologyPoolList)) {
            throw new GlobalRunTimeException(errorMessage);
        }
        Optional<EcologyPool> optional = ecologyPoolList.stream().filter(ecologyPool -> Objects.equals(ecologyPool.getPoolType().getCode(), poolType.getCode())).findFirst();
        if (optional.isPresent()) {
            EcologyPool ecologyPool = optional.get();
            if (ecologyPool.getLinkCount().compareTo(BigDecimal.valueOf(linkCount)) < 0) {
                throw new GlobalRunTimeException(errorMessage);
            }
        } else {
            throw new GlobalRunTimeException(errorMessage);
        }
    }

    /**
     * 校验优秀品牌池分配/扣除参数
     *
     * @param operationType
     * @param daoId
     * @param linkCount
     * @param linkType
     */
    private List<EcologyPool> validateExcellentBrandAllocatePoints(EcologyPoolOperationTypeEnum operationType, Long daoId, Long linkCount, EcologyPoolLinkTypeEnum linkType) {
        Assert.isTrue(linkCount > 0, () -> new GlobalRunTimeException(ErrorCode.LINK_COUNT_GT_ZERO));
        //region 校验品牌是否开启入榜
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(daoId);
        Assert.isTrue(Objects.nonNull(userCreatorInfo), () -> new GlobalRunTimeException(ErrorCode.BRAND_NOT_NULL));
        Assert.isTrue(userCreatorInfo.getEnableJoinRank(), () -> new GlobalRunTimeException(ErrorCode.BRAN_NOT_ENABLE_JOIN));
        //endregion
        //region 校验积分是否足够
        List<EcologyPool> ecologyPoolList = new ArrayList<>();
        EcologyPool ecologyPool = ecologyPoolDao.getByType(EcologyPoolTypeEnum.EXCELLENT_BRAND, linkType);
        if (Objects.nonNull(ecologyPool)) {
            ecologyPoolList.add(ecologyPool);
        }
        ecologyPool = ecologyPoolDao.getByTypeAndDaoId(EcologyPoolTypeEnum.BRAND, linkType, daoId);
        if (Objects.nonNull(ecologyPool)) {
            ecologyPoolList.add(ecologyPool);
        }
        if (Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode())) {
            validateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.EXCELLENT_BRAND, linkCount, EcologyPoolTypeEnum.EXCELLENT_BRAND.getDesc() + "积分不足");
        } else {
            validateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.BRAND, linkCount, EcologyPoolTypeEnum.BRAND.getDesc() + "积分不足");
        }
        //endregion
        return ecologyPoolList;
    }

    /**
     * 执行优秀品牌池分配/扣除
     *
     * @param ecologyPoolList
     * @param operationType
     * @param daoId
     * @param linkCount
     * @param linkType
     * @param remark
     */
    private void doExcellentBrandAllocatePoints(List<EcologyPool> ecologyPoolList, EcologyPoolOperationTypeEnum operationType, Long daoId, Long linkCount, EcologyPoolLinkTypeEnum linkType, String remark) {
        if (Objects.equals(operationType.getCode(), EcologyPoolOperationTypeEnum.PLUS.getCode())) {
            //扣减优秀品牌生态池积分
            Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.EXCELLENT_BRAND, BigDecimal.valueOf(linkCount));
            Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.BRAND, BigDecimal.valueOf(linkCount), linkType, daoId, null);
            //添加变动记录
            doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(linkCount), linkType, operationType, remark);
        } else {
            //增加优秀品牌生态池积分
            Long targetEcologyPoolId = doPlusUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.EXCELLENT_BRAND, BigDecimal.valueOf(linkCount), linkType, META_DAO_ID, null);
            Long sourceEcologyPoolId = doReduceUpdateEcologyPool(ecologyPoolList, EcologyPoolTypeEnum.BRAND, BigDecimal.valueOf(linkCount));
            //添加变动记录
            doNewEcologyPoolRecord(sourceEcologyPoolId, targetEcologyPoolId, BigDecimal.valueOf(linkCount), linkType, operationType, remark);
        }
    }

}
